Reputation: 407
I have a GridView
, to which I have written a DataBound function to assign a tooltip. But it is not getting assigned. The function I have written is:
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();
}
}
}
When I debug the label2 is null. The same code is executing for another Grid. What is wrong...!! Kindly help..!
Upvotes: 1
Views: 9744
Reputation: 407
Having a TemplateField and then using the ID of the ItemTemplate, solves the problem.
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();
}
}
}
Upvotes: 0
Reputation: 25810
Hmmm... prehaps this is the problem?
// **************
foreach (GridViewRow row in GridView3.Rows)
Should be?
// **
foreach (GridViewRow row in gv.Rows)
EDIT
Ah! Cells is a zero-based array. If you want the second cell, you need to use the array index 1.
This:
// *
string label2 = row.Cells[2].Text.Trim();
Should be:
// *
string label2 = row.Cells[1].Text.Trim();
EDIT
Using the numeric cell index is very hard to read and very fragile. If you add a column, or remove a column, all of your code will break. I highly recommend using the cell name, like so:
// ************
string label2 = row[Label10.Text].Text.Trim();
EDIT
Maybe this would work better for you?
string label2 = ( (DataRow) row.DataItem )[Label10.Text].ToString().Trim();
Upvotes: 2