0

我正在尝试使用 gridview 标题模板插入 sql 表,在 gridview 行命令下我试图找到控件并且它无法检索值。

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

任何帮助深表感谢

4

1 回答 1

0

您可以尝试RowDataBound事件来获取标题模板控件。

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

编辑 1

从为 GridView 标记共享的链接中,TextBox31 不在 HeaderItemTemplate 中,它在 EditItemTemplate 中。这就是原因,您无法找到文本框。

 <EditItemTemplate>
                        <asp:TextBox ID="TextBox31" runat="server" Text='<%# Bind("Field4") %>'></asp:TextBox>
                    </EditItemTemplate>
于 2016-01-26T18:48:50.223 回答