Hi lingers,
Refer below modified code of btnInsert_Click event and Insert function.
Rest your code is ok.
protected void btnInsert_Click(object sender, System.EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[] { new DataColumn("StateId"), new DataColumn("State"), new DataColumn("Statecolour") });
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 tbState = uc.FindControl("txtState") as TextBox;
TextBox tbStateId = uc.FindControl("txtStateId") as TextBox;
TextBox tbStateClr = uc.FindControl("txtStateClr") as TextBox;
if (!string.IsNullOrEmpty(tbStateId.Text.Trim()) && !string.IsNullOrEmpty(tbState.Text.Trim()) && !string.IsNullOrEmpty(tbStateClr.Text.Trim()))
{
dt.Rows.Add(tbStateId.Text.Trim(), tbState.Text.Trim(), tbStateClr.Text.Trim());
Insert(tbState.Text.Trim(), tbStateId.Text.Trim(), tbStateClr.Text.Trim());
}
}
}
gvInsertedRecords.DataSource = dt;
gvInsertedRecords.DataBind();
}
private void Insert(string state, string id, string Statecolour)
{
string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string query = "INSERT INTO tblStates (StateId, State, Statecolour) VALUES (@StateId, @State, @Statecolour)";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("@StateId", id);
cmd.Parameters.AddWithValue("@State", state);
cmd.Parameters.AddWithValue("@Statecolour", Statecolour);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
Make sute the Insert query column name same as in the database table column.