C#中dataGridView的问题

选中dataGridView某行..点button可实现删除该行,并更新库..
求form代码

第1个回答  2008-04-09
包括删除和编辑的全部代码:
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
{

//清清月儿http://blog.csdn.net/21aspnet
SqlConnection sqlcon;
SqlCommand sqlcom;
string strCon = "Data Source=(local);Database=数据库名;Uid=帐号;Pwd=密码";
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" };//主键
GridView1.DataBind();
sqlcon.Close();
}
}
第2个回答  2008-04-09
直接给你看代码相信你会晕 我给你一点灵感
datagrideview不是有一个currentrow的属性吗
datagrideview[0,datagrideviewrow.currentrow]就是他的第一个列的数据 剩下的你应该知道怎么做了吧本回答被提问者采纳
第3个回答  2008-04-09
GridView1.DataKeyNames = new string[] { "主键" };
写在LOAD中.

protected void btnDel_Click(object sender, EventArgs e)
{
for (int i = 0; i < this.GridView1.Rows.Count; i++)
{
if (((CheckBox)this.GridView1.Rows[i].Cells[0].FindControl("chkSelect")).Checked)
{
OA_Business.Employer.Employer epy = new OA_Business.Employer.Employer();
epy.E_ID = int.Parse(GridView1.DataKeys[i].Value.ToString());
epy.E_Del();
}
}
BindEmployer();
}

这是一个用CheckBox选中删除的用于多选的.
第4个回答  2008-04-09
dataGridView.selectedItems[0].remove();
第5个回答  2008-04-09
很多方式处理这个东西的
相似回答