日期:2014-05-20  浏览次数:20431 次

关于asp.net中的DataGrid数据批量更新
在asp.net中,我用DataSet获取。在DataGrid中绑定DataSet.Tables[ "*** "].DefaultView,现在我在DataGrid修改了一些数据,我要怎么样才能批量更新数据呢,是把DataGrid中的行都取出来然后用update来更新吗?
在线等答案,也可以QQ:261766987

------解决方案--------------------
参考:

/// <summary>
/// WebForm2 的摘要说明。
/// </summary>
public class WebForm2 : System.Web.UI.Page
{
private string strcon = "server=localhost;database=pubs;uid=sa;pwd=wang ";
protected System.Web.UI.WebControls.DataGrid DataGrid1;

private void Page_Load(object sender, System.EventArgs e)
{
if(!IsPostBack)
{
BindGrid();
}
}
private void BindGrid()
{
System.Data.SqlClient.SqlConnection con=new System.Data.SqlClient.SqlConnection(strcon);
string sql= "select top 5 * from authors order by au_id desc ";
System.Data.SqlClient.SqlCommand cmd=new System.Data.SqlClient.SqlCommand(sql,con);
con.Open();
DataGrid1.DataSource = cmd.ExecuteReader();
DataGrid1.DataBind();
con.Close();
}

#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.DataGrid1.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_ItemCommand);
this.DataGrid1.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.DataGrid1_ItemDataBound);
this.Load += new System.EventHandler(this.Page_Load);

}
#endregion

private void DataGrid1_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
if(e.Item.ItemType == ListItemType.Footer)
{
if(e.CommandName== "edit ")
{
for(int i=0;i < DataGrid1.Items.Count;i++)
{

TextBox t1=new TextBox();
t1=(TextBox)DataGrid1.Items[i].FindControl( "TextBox1 ");

TextBox t2=new TextBox();
t2=(TextBox)DataGrid1.Items[i].FindControl( "TextBox2 ");
string id=DataGrid1.Items[i].Cells[0].Text;
string sql= "update authors set au_fname= ' "+t1.Text+ " ',au_lname= ' "+t2.Text+ " ' where au_id= ' "+id+ " ' ";
if(Microsoft.ApplicationBlocks.Data.SqlHelper.ExecuteNonQuery(strcon,CommandType.Text,sql)!=1)
{
Response.Write( "更新失败! ");
return;
}

//Response.Write( " <Li> ID: "+DataGrid1.Items[i].Cells[0].Text);
//Response.Write( "更新内容1: " + t1.Text);
//Response.Write( "更新内容2: " + t2.Text);

}

BindGrid();
}
}
}

private void DataGrid1_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
//if(e.Item.ItemType == ListItemType.Footer)
//{
//Button b1=(Button)e.Item.FindControl( "Button1 ");
//b1.Attributes.Add( "onclick ", "return confirm( '您真的要全部更新吗? '); ");
//}

if(e.Item.ItemType== ListItemType.Item || e.Item.ItemType== ListItemType.AlternatingItem)
{
TextBox t1,t2;
t1=(TextBox)e.Item.FindControl( "TextBox1 ");
t1.Attributes.Add( "onfocus ", "this.className= 'edit ' ");