2016-01-26 33 views
0

我想要插入到使用gridview標題模板,在gridview rowcommand下的sql表,我試圖找到控件,它無法檢索值。GridViewRowCommand無法找到標題行文本框值

protected void GridView1_RowCommand1(object sender, GridViewCommandEventArgs e) 
{ 
    if (e.CommandName == "Insert") 
    { 
     string NetWeightConnectionStrings = ConfigurationManager.ConnectionStrings["NetWeightConnectionString"].ToString(); 
     string query = "INSERT INTO [Net Weight Tracking] ([Date])VALUES (@Date)"; 
     using (SqlConnection sqlConn = new SqlConnection(NetWeightConnectionStrings)) 
     using (SqlCommand cmd = new SqlCommand(query, sqlConn)) 
     { 
      String Date = ((TextBox)GridV1.HeaderRow.FindControl("TextBox31")).Text; 
      cmd.Parameters.Add("@Date", SqlDbType.DateTime).Value = DateTime.ParseExact(((TextBox)GridV1.HeaderRow.FindControl("TextBox31")).Text, "dd/MM/yyyy", null); 
      sqlConn.Open(); 
      DataTable dt = new DataTable(); 
      dt.Load(cmd.ExecuteReader()); 
      GridV1.DataSource = dt; 
      GridV1.DataBind(); 
      sqlConn.Close(); 
     } 
    } 
} 

任何的幫助深表感謝

+0

這個TextBox31位於標題行嗎? – Agalo

+0

@Agalo它位於HeaderTemplate –

回答

0

你可以嘗試RowDataBound事件獲得頭模板對照。

protected void GridView1__RowDataBound(object sender, GridViewRowEventArgs e) 
    { 
     if (e.Row.RowType == DataControlRowType.Header) 
     { 
      TextBox txtControl = (TextBox)e.Row.FindControl("TextBox31"); 
     } 
    } 

EDIT 1

從爲GridView馬克共享所述鏈路TextBox31不在HeaderItemTemplate,它是在EditItemTemplate中。這就是原因,你無法找到文本框。

<EditItemTemplate> 
         <asp:TextBox ID="TextBox31" runat="server" Text='<%# Bind("Field4") %>'></asp:TextBox> 
        </EditItemTemplate> 
+0

下,但我需要在受保護的無效GridView1_RowCommand1(對象發件人,GridViewCommandEventArgs e) –

+0

你可以粘貼gridview的aspx頁面標記嗎? – Agalo

+0

我的gridview的整個aspx可以在http://pastebin.com/MbU6fn9V看到 –