2012-09-28 46 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(); 
      } 
     } 
    }