如何将文本框中的值添加到数据库& Gridview同时进行
问题描述:
SqlConnection con = new SqlConnection("MyConnection String");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO Emp_tab1 (Emp_name,Emp_Sal ) VALUES ('" +TextBox1.Text +"', '" + TextBox2.Text + "')", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
con.Close();
}
}
但它给出了Exeption,因为IListSource不包含任何数据源。
所以,如果有人对此有任何答复,请回复。
提前致谢。
But it gives the Exeption as The IListSource does not contain any data sources.
So if anyone has any answer for this please reply.
Thanks in advance.
答
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadGridData();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlCommand cmd = new SqlCommand("INSERT INTO Emp_tab1 (Emp_name,Emp_Sal ) VALUES ('"+TextBox1.Text +"', " + Convert.ToDecimal(TextBox2.Text) + ")", con); // If Salary Data Type In database Decimal
con.Open();
cmd.ExecuteNonQuery();
con.Close();
LoadGridData();
}
}
public void LoadGridData() // Bind GridView Data
{
SqlCommand cmd = new SqlCommand("select * from Emp_tabl1", con);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}