如何将项目模板文本框从gridview保存到数据库

时间:2012-09-08 06:16:40

标签: c# asp.net ado.net

我有一个gridview,其中包含2个项目模板1复选框2文本框,如下所示:

<asp:GridView 
    ID="Warehouse_gv" 
    runat="server" 
    AllowPaging="True" 
    align="center" 
    AllowSorting="True" AutoGenerateColumns="False" 
    DataSourceID="Warehouse_gv_SqlDS"
    onselectedindexchanged="Warehouse_gv_SelectedIndexChanged" 
    Width="230px" PageSize="700">

 <Columns>
    <asp:CommandField ShowDeleteButton="False" ShowEditButton="True" />
    <asp:TemplateField HeaderText="Select">
       <ItemTemplate>
            <asp:CheckBox ID="chkSelect" runat="server" />
      </ItemTemplate>

      <HeaderTemplate>
       <input id="chkAll"  
             önclick="javascript:SelectAllCheckboxes(this);" 
             runat="server" type="checkbox" />
      </HeaderTemplate>
    </asp:TemplateField>

    <asp:BoundField DataField="Line Number" 
                    HeaderText="Line Number" ReadOnly="True" 
                    SortExpression="Line Number" />
    <asp:BoundField DataField="Reference" 
                    HeaderText="Reference" ReadOnly="True" 
                    SortExpression="Reference" />
    <asp:BoundField DataField="QTY" HeaderText="QTY"
                    SortExpression="QTY" />

    <asp:TemplateField HeaderText="EditQTY">
      <ItemTemplate>
          <asp:TextBox ID ="test" runat="server" />
     </ItemTemplate>
     <HeaderTemplate>
          EditQTY
     </HeaderTemplate>
    </asp:TemplateField>
   </Columns>
  <EmptyDataTemplate>
    No data could be find!
  </EmptyDataTemplate>
</asp:GridView>

此网格有6列1-editbutton 2-checkbox(第一项模板)3-lineNo 4-reference 5-number 6-editqty(第二项模板)。 但是当我想将这个gridview中的数据保存到另一个数据库时,对于我放入项目模板字段数据的文本框字段(EditQTY列)不会传输这是我的代码背后:

protected void SAVE_btn_Click(object sender, EventArgs e)
    {
        int C = 0;

        for (int i = 0; i < Warehouse_gv.Rows.Count; i++)
        {
            GridViewRow row = Warehouse_gv.Rows[i];
            bool isChecked = ((CheckBox)row.FindControl("chkSelect")).Checked;

            if (isChecked)
            {
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = new SqlConnection(Class1.CnnStr);
                cmd.CommandText = "insert into WarehousePart values (@Reference,@EditQty)";
                cmd.Connection.Open();
                cmd.Parameters.AddWithValue("@Reference", Warehouse_gv.Rows[i].Cells[3].Text); 
                cmd.Parameters.AddWithValue("@EditQty", Warehouse_gv.Rows[i].Cells[5].Text);
                cmd.ExecuteNonQuery();
                cmd.Connection.Close();
                C = C + 1;
            }
        }
    }.

1 个答案:

答案 0 :(得分:2)

您必须使用FindControl方法获取ID为TextBox的{​​{1}}的引用。

test