我有一个GridView
,我已经编写了一个DataBound函数来分配工具提示。但它没有被分配。我写的函数是:
SqlCommand comd = new SqlCommand("SELECT Location_Profile_Name, " + Label10.Text + " as Home_Profile FROM Home_Profile_Master", con);
SqlDataAdapter da = new SqlDataAdapter(comd);
DataTable dt = new DataTable();
da.Fill(dt);
GridView3.DataSource = dt;
GridView3.DataBind();
protected void GridView3_DataBound(object sender, EventArgs e)
{
var gv = (GridView)sender;
foreach (GridViewRow row in GridView3.Rows)
{
string label2 = row.Cells[2].Text.Trim();
if (label2.Length != 0)
{
con.Open();
string str = "SELECT Location_Profile_Tool_Tip FROM Location_Profile_List_ToolTip WHERE Location_Profile_Name='" + label2 + "'";
SqlCommand cmd = new SqlCommand(str, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
row.Cells[2].ToolTip = dr[0].ToString().Trim();
}
con.Close();
}
}
}
当我调试 label2 为空时。另一个Grid正在执行相同的代码。怎么了...!!请帮助..!
答案 0 :(得分:2)
// **************
foreach (GridViewRow row in GridView3.Rows)
应该是吗?
// **
foreach (GridViewRow row in gv.Rows)
修改强>
啊! Cells是一个从零开始的数组。如果需要第二个单元格,则需要使用数组索引1。
此:
// *
string label2 = row.Cells[2].Text.Trim();
应该是:
// *
string label2 = row.Cells[1].Text.Trim();
修改强>
使用数字单元格索引非常难以阅读且非常脆弱。如果添加列或删除列,则所有代码都将中断。我强烈建议使用单元名称,如下所示:
// ************
string label2 = row[Label10.Text].Text.Trim();
修改强>
也许这对你有用吗?
string label2 = ( (DataRow) row.DataItem )[Label10.Text].ToString().Trim();
答案 1 :(得分:0)
拥有TemplateField,然后使用ItemTemplate的ID,解决问题。
protected void GridView3_DataBound(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView3.Rows)
{
Label label1 = (Label)row.FindControl("Label1"); //ID of the ItemTemplate for my column to which I want ToolTip
string label2 = label1.Text.Trim();
if (label2.Length != 0)
{
con.Open();
string str = "SELECT Location_Profile_Tool_Tip FROM Location_Profile_List_ToolTip WHERE Location_Profile_Name='" + label2 + "'";
SqlCommand cmd = new SqlCommand(str, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
row.Cells[2].ToolTip = dr[0].ToString().Trim();
}
con.Close();
}
}
}