2012-09-28 35 views
1

我有一个GridView,我写了一个DataBound函数来分配工具提示。但它没有被分配。我写的功能是: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为空。相同的代码正在执行另一个网格。哪里不对...!!请帮助..!

+1

显示,其中标签放置一排 – sll

+0

看看里面你的代码再次声明了例如GV事情,但在代码中,你使用它ASPX/ASCX的一部分?? – MethodMan

+0

'label2'不能为null,它的长度可以是0。 –

回答

2

嗯...可能这是问题吗?

//       ************** 
foreach (GridViewRow row in GridView3.Rows) 

应该是?

//       ** 
foreach (GridViewRow row in gv.Rows) 

编辑

啊!单元格是一个从零开始的数组。如果你想在第二个单元格,则需要使用数组索引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(); 
+0

Nope Cells [2],cos我的第一列是编辑,第二个Details是我分配的另一个链接,第三是我的工具提示数据。 –

+0

您确定您的DataBoundColumn安装正确吗?使用正确的列名称? – JDB

+0

是的,至少如果不是该列的工具提示应该显示其他列kw ..? –

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(); 
      } 
     } 
    }