日期:2014-05-18  浏览次数:21079 次

如何在DataGrilView中直接添加修改数据?
能否告知一下具体的操作方法和详细代码

------解决方案--------------------
这些网上都有,msdn上很多。
------解决方案--------------------
http://blog.csdn.net/21aspnet/archive/2007/03/25/1540301.aspx


看看这个,清清月儿的GridView72般绝技,你一定喜欢的~


------解决方案--------------------
我也想学习这个,帮楼主顶.
------解决方案--------------------
mark
------解决方案--------------------
后台代码:
C# code
using System; 
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
  SqlConnection sqlcon;
  SqlCommand sqlcom;
  string strCon = "Data Source=(local);Database=MyDB;Uid=SA;Pwd=SA";
  protected void Page_Load(object sender, EventArgs e)
  {
    if (!IsPostBack)
    {
      bind();
    }
  }
  protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
  {
    GridView1.EditIndex = e.NewEditIndex;
    bind();
  }
//删除
  protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
  {
    string sqlstr = "delete from 表 where id='" + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'";
    sqlcon = new SqlConnection(strCon);
    sqlcom = new SqlCommand(sqlstr,sqlcon);
    sqlcon.Open();
    sqlcom.ExecuteNonQuery();
    sqlcon.Close();
    bind();
  }
//更新
  protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
  {
    sqlcon = new SqlConnection(strCon);
    string sqlstr = "update 表 set 字段1='"
      + ((TextBox)(GridView1.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim() + "',字段2='"
      + ((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text.ToString().Trim() + "',字段3='"
      + ((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString().Trim() + "' where id='"
      + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'";
    sqlcom=new SqlCommand(sqlstr,sqlcon);
    sqlcon.Open();
    sqlcom.ExecuteNonQuery();
    sqlcon.Close();
    GridView1.EditIndex = -1;
    bind();
  }
//取消
  protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
  {
    GridView1.EditIndex = -1;
    bind();
  }
//绑定
  public void bind()
  {
    string sqlstr = "select * from 表";
    sqlcon = new SqlConnection(strCon);
    SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);
    DataSet myds = new DataSet();
    sqlcon.Open();
    myda.Fill(myds, "表");
    GridView1.DataSource = myds;
    GridView1.DataKeyNames = new string[] { "id" };//主键