如何将文本框中的值添加到数据库& Gridview同时进行 [英] How to add the value from textbox to Database & Gridview simultaneously

查看:79
本文介绍了如何将文本框中的值添加到数据库& 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();

                    }


这篇关于如何将文本框中的值添加到数据库& Gridview同时进行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆