Data Inserted not showing in dabase table but appears in Gridview when inserted.
This example below displays data in textbox when Listbox data is clicked, but when i insert the data into database it only shows on the GridView but when i check my table in database the record is not there.
protected void btnInsert_Click(object sender, System.EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[] { new DataColumn("Item"), new DataColumn("Price"), new DataColumn("Quantity") });
foreach (Control c in ph1.Controls)
{
//Find the specific user control that we added to this placeholder, and then get the selected values
//for the dropdownlist, checkbox, and textbox and print them to the screen.
if (c.GetType().Name.ToLower() == "usercontrol_ascx")
{
UserControl uc = (UserControl)c;
TextBox tbItem = uc.FindControl("txtItem") as TextBox;
TextBox tbPrice = uc.FindControl("txtPrice") as TextBox;
TextBox tqty = uc.FindControl("txtQuantity") as TextBox;
if (!string.IsNullOrEmpty(tbItem.Text.Trim()) && !string.IsNullOrEmpty(tbPrice.Text.Trim()) && !string.IsNullOrEmpty(tqty.Text.Trim()))
{
dt.Rows.Add(tbItem.Text.Trim(), tbPrice.Text.Trim(), tqty.Text.Trim());
//Insert(tbStateId.Text.Trim(), tbState.Text.Trim());
}
}
}
gvInsertedRecords.DataSource = dt;
gvInsertedRecords.DataBind();
}
private void Insert(string item, string price, string qty)
{
string constr = ConfigurationManager.ConnectionStrings["DB"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string query = "INSERT INTO tblStates2 VALUES (@Item, @Price, @Quantity)";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("@Item", item);
cmd.Parameters.AddWithValue("@Price", price);
cmd.Parameters.AddWithValue("@Quantity", qty);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
<asp:Button ID="btnInsert" runat="server" Text="Insert" OnClick="btnInsert_Click" CssClass="btn btn-default"/>
<br />
<br />
<asp:GridView runat="server" ID="gvInsertedRecords" />