如何在表格中显示数据?

时间:2014-01-11 23:10:24

标签: c#

我是C#的初学者并使用MS Visual Studio 2010.我的问题是我通过文本框在名为(tbl_employees)的表中插入数据并成功保存。

在看到表格后保存后,即使在更新后,新插入的数据也未显示在tbl_employee中。

这是我更新表格的代码

private void btnupdate_Click(object sender, EventArgs e)
{
     System.Data.SqlClient.SqlDataAdapter da;
     string sql = "SELECT * From tbl_employees";
     da = new System.Data.SqlClient.SqlDataAdapter(sql , conString);
     System.Data.SqlClient.SqlCommandBuilder cb;
     cb = new System.Data.SqlClient.SqlCommandBuilder(da);
     DataRow row = ds.Tables[0].Rows[inc];
     dRow[1] = textBox1.Text;
     dRow[2] = textBox2.Text;
     MaxRows = MaxRows + 1; //to enable last row is still last row
     inc = MaxRows - 1;

     MessageBox.Show("Now Table is updated too. . . ");
}

1 个答案:

答案 0 :(得分:1)

易于理解和实施代码

插入

private void Insert()
{
   using(SqlConnection conn = new SqlConnection(yourConnString) )
   {
     string qry = "Insert into YourTable Select (@Val1,@Val2,@Val3)";
     using(SqlCommand command = new SqlCommand(qry,conn))
     {
       conn.Open();
       command.CommandType= CommandType.Text;
       command.Parameters.Add("@Val1",txt1.Text);
       command.Parameters.Add("@Val2",txt2.Text);
       command.Parameters.Add("@Val3",txt3.Text);
       int i = command.ExecuteNonQuery();
       con.Close();
     }


   }
}

更新

 private void Update()
    {
       using(SqlConnection conn = new SqlConnection(yourConnString) )
       {
         string qry = "Update YourTable Set Field1=@Val1,Field2=@Val2,Field3=@Val3 Where YourPrimaryKey=@Key";
         using(SqlCommand command = new SqlCommand(qry,conn))
         {
           conn.Open();
           command.CommandType= CommandType.Text;
           command.Parameters.Add("@Val1",txt1.Text);
           command.Parameters.Add("@Val2",txt2.Text);
           command.Parameters.Add("@Val3",txt3.Text);
           command.Parameters.Add("@Key",txt4.Text);
           int i = command.ExecuteNonQuery();
           con.Close();
         }


       }
    }

选择

 private DataTable Get()
    {
       DataTable dt = new DataTable();
       using(SqlConnection conn = new SqlConnection(yourConnString) )
       {
         string qry = "Select * From YourTable";
         using(SqlCommand command = new SqlCommand(qry,conn))
         {
           conn.Open();
           command.CommandType= CommandType.Text;
          using(var reader = command.ExecuteReader(CommandBehaviour.CloseConnection))
         {
            dt.Load(reader);
         }

           con.Close();
         }


       }
      return dt;
    }

现在你有了一个返回DataTable的Get方法,现在你需要一个网格来显示那些数据。很简单。

ASP.Net

private void BindGrid()
{
   gridview1.DataSource = Get();
   gridView1.DataBind();
}

的Winforms

与上述相同,但我们无需致电DataBind()