I am trying to insert every row from the gridview into a database through the click of a button. The code works with no errors, but nothing is actually being inserted into the database, can anyone spot what I've done wrong? Here is the c# code from my button event.
protected void btnSubmit_Click(object sender, EventArgs e)
{
int index = 0;
foreach (GridViewRow row in gvStockTake.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
Label ID = gvStockTake.Rows[index].FindControl("itemId")as Label;
TextBox BAR = gvStockTake.Rows[index].FindControl("txtBar") as TextBox;
TextBox STORAGE = gvStockTake.Rows[index].FindControl("txtStorage") as TextBox;
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText =
"insert into Stock_Take_Item(ItemID, BarQuantity, StorageQuantity) values(@ID, @BAR, @STORAGE) ";
cmd.Parameters.Add("@ID", SqlDbType.VarChar).Value = ID.Text;
cmd.Parameters.Add("@BAR", SqlDbType.Int).Value = BAR.Text;
cmd.Parameters.Add("@STORAGE", SqlDbType.Int).Value = STORAGE.Text;
}
index++;
}
Response.Write("Successfully inserted stock take items.");
}
Here is the code for populating my Gridview:
void PopulateGridview()
{
DataTable dtbl = new DataTable();
using (SqlConnection sqlCon = new SqlConnection(connectionString))
{
sqlCon.Open();
SqlDataAdapter sqlDa = new SqlDataAdapter("SELECT Item.ItemID, Item.ItemDesc, Stock_Take_Item.BarQuantity, Stock_Take_Item.StorageQuantity FROM Item LEFT JOIN Stock_Take_Item ON Item.ItemID = Stock_Take_Item.ItemID", sqlCon);
sqlDa.Fill(dtbl);
}
gvStockTake.DataSource = dtbl;
gvStockTake.DataBind();
}
Here is the code for my Gridview (I have deleted all styling properties for shortening purposes)
<pre><asp:GridView ID="gvStockTake" runat="server" AutoGenerateColumns="false" ShowHeaderWhenEmpty="true"
<Columns>
<asp:TemplateField HeaderText="Item ID">
<ItemTemplate>
<asp:Label id="itemId" Text='<%# Eval("ItemID")%>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Item Description">
<ItemTemplate>
<asp:Label Text='<%# Eval("ItemDesc")%>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Bar Quantity">
<ItemTemplate>
<asp:TextBox ID="txtBar" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Storage Quantity">
<ItemTemplate>
<asp:TextBox ID="txtStorage" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I am still learning as i'am going, so any recommendations would be greatly appreciated!
What I have tried:
I have been playing with this code for ages and can't figure out why it's not inserting correctly.