Datagrid怎么根据选择的checkbox编辑和更新多行记录?
有网友问这个问题,写了一个简单的例子:
前台:
<%@ Page language="c#" Codebehind="WebForm4.aspx.cs" AutoEventWireup="false" Inherits="WebApplication25.WebForm4" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>WebForm4</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>
<body>
<form id="Form1" method="post" runat="server">
<asp:DataGrid id="DataGrid1" runat="server" AutoGenerateColumns="False" DataKeyField="EmployeeID">
<Columns>
<asp:TemplateColumn>
<ItemTemplate>
<input type="hidden" id="SelectedID" runat="server" value='<%# Container.ItemIndex%>' name="SelectedID"/>
<asp:CheckBox ID="chkExport" Runat="server" />
</ItemTemplate>
</asp:TemplateColumn>
<asp:BoundColumn DataField="EmployeeID" HeaderText="EmployeeID"></asp:BoundColumn>
<asp:TemplateColumn HeaderText="FirstName">
<ItemTemplate>
<asp:Label ID="lab_FirstName" Runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"FirstName")%>'>
</asp:Label>
<asp:TextBox ID="txt_FirstName" Runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"FirstName")%>' Visible="False">
</asp:TextBox>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="LastName">
<ItemTemplate>
<asp:Label ID="lab_LastName" Runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"LastName")%>'>
</asp:Label>
<asp:TextBox ID="txt_LastName" Runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"LastName")%>' Visible="False">
</asp:TextBox>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
<asp:Button id="Button1" runat="server" Text="编辑"></asp:Button>
<asp:Button id="Button2" runat="server" Text="更新"></asp:Button>
</form>
</body>
</HTML>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>WebForm4</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>
<body>
<form id="Form1" method="post" runat="server">
<asp:DataGrid id="DataGrid1" runat="server" AutoGenerateColumns="False" DataKeyField="EmployeeID">
<Columns>
<asp:TemplateColumn>
<ItemTemplate>
<input type="hidden" id="SelectedID" runat="server" value='<%# Container.ItemIndex%>' name="SelectedID"/>
<asp:CheckBox ID="chkExport" Runat="server" />
</ItemTemplate>
</asp:TemplateColumn>
<asp:BoundColumn DataField="EmployeeID" HeaderText="EmployeeID"></asp:BoundColumn>
<asp:TemplateColumn HeaderText="FirstName">
<ItemTemplate>
<asp:Label ID="lab_FirstName" Runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"FirstName")%>'>
</asp:Label>
<asp:TextBox ID="txt_FirstName" Runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"FirstName")%>' Visible="False">
</asp:TextBox>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="LastName">
<ItemTemplate>
<asp:Label ID="lab_LastName" Runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"LastName")%>'>
</asp:Label>
<asp:TextBox ID="txt_LastName" Runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"LastName")%>' Visible="False">
</asp:TextBox>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
<asp:Button id="Button1" runat="server" Text="编辑"></asp:Button>
<asp:Button id="Button2" runat="server" Text="更新"></asp:Button>
</form>
</body>
</HTML>
后台:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace WebApplication25
{
/// <summary>
/// WebForm4 的摘要说明。
/// </summary>
public class WebForm4 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Button Button1;
protected System.Web.UI.WebControls.Button Button2;
protected System.Web.UI.WebControls.DataGrid DataGrid1;
protected System.Web.UI.HtmlControls.HtmlInputHidden SelectID;
private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
if(!IsPostBack)
{
SetBind();
}
}
private void SetBind()
{
SqlConnection conn=new SqlConnection("server=srvxglai-sha;uid=sa;pwd=321413;database=northwind");
SqlDataAdapter da=new SqlDataAdapter("select * from Employees",conn);
DataSet ds=new DataSet();
da.Fill(ds,"table1");
this.DataGrid1.DataSource=ds.Tables["table1"];
this.DataGrid1.DataBind();
}
#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.Button1.Click += new System.EventHandler(this.Button1_Click);
this.Button2.Click += new System.EventHandler(this.Button2_Click);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
private void Button1_Click(object sender, System.EventArgs e)
{
foreach(DataGridItem di in this.DataGrid1.Items)
{
if(((CheckBox)di.FindControl("chkExport")).Checked==true)
{
((TextBox)di.FindControl("txt_FirstName")).Visible=true;
((TextBox)di.FindControl("txt_LastName")).Visible=true;
((Label)di.FindControl("lab_FirstName")).Visible=false;
((Label)di.FindControl("lab_LastName")).Visible=false;
}
}
}
private void Button2_Click(object sender, System.EventArgs e)
{
foreach(DataGridItem di in this.DataGrid1.Items)
{
if(((CheckBox)di.FindControl("chkExport")).Checked==true)
{
if(((TextBox)di.FindControl("txt_FirstName")).Text!=((Label)di.FindControl("lab_FirstName")).Text||((TextBox)di.FindControl("txt_LastName")).Text!=((Label)di.FindControl("lab_LastName")).Text)
{
Response.Write("记录号:"+this.DataGrid1.DataKeys[int.Parse(((HtmlInputHidden)di.FindControl("SelectedID")).Value)]+",FirstName:"+((TextBox)di.FindControl("txt_FirstName")).Text+",LastName:"+((TextBox)di.FindControl("txt_LastName")).Text+"<br>");
}
((TextBox)di.FindControl("txt_FirstName")).Visible=false;
((TextBox)di.FindControl("txt_LastName")).Visible=false;
((Label)di.FindControl("lab_FirstName")).Visible=true;
((Label)di.FindControl("lab_LastName")).Visible=true;
((CheckBox)di.FindControl("chkExport")).Checked=false;
}
}
}
}
}
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace WebApplication25
{
/// <summary>
/// WebForm4 的摘要说明。
/// </summary>
public class WebForm4 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Button Button1;
protected System.Web.UI.WebControls.Button Button2;
protected System.Web.UI.WebControls.DataGrid DataGrid1;
protected System.Web.UI.HtmlControls.HtmlInputHidden SelectID;
private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
if(!IsPostBack)
{
SetBind();
}
}
private void SetBind()
{
SqlConnection conn=new SqlConnection("server=srvxglai-sha;uid=sa;pwd=321413;database=northwind");
SqlDataAdapter da=new SqlDataAdapter("select * from Employees",conn);
DataSet ds=new DataSet();
da.Fill(ds,"table1");
this.DataGrid1.DataSource=ds.Tables["table1"];
this.DataGrid1.DataBind();
}
#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.Button1.Click += new System.EventHandler(this.Button1_Click);
this.Button2.Click += new System.EventHandler(this.Button2_Click);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
private void Button1_Click(object sender, System.EventArgs e)
{
foreach(DataGridItem di in this.DataGrid1.Items)
{
if(((CheckBox)di.FindControl("chkExport")).Checked==true)
{
((TextBox)di.FindControl("txt_FirstName")).Visible=true;
((TextBox)di.FindControl("txt_LastName")).Visible=true;
((Label)di.FindControl("lab_FirstName")).Visible=false;
((Label)di.FindControl("lab_LastName")).Visible=false;
}
}
}
private void Button2_Click(object sender, System.EventArgs e)
{
foreach(DataGridItem di in this.DataGrid1.Items)
{
if(((CheckBox)di.FindControl("chkExport")).Checked==true)
{
if(((TextBox)di.FindControl("txt_FirstName")).Text!=((Label)di.FindControl("lab_FirstName")).Text||((TextBox)di.FindControl("txt_LastName")).Text!=((Label)di.FindControl("lab_LastName")).Text)
{
Response.Write("记录号:"+this.DataGrid1.DataKeys[int.Parse(((HtmlInputHidden)di.FindControl("SelectedID")).Value)]+",FirstName:"+((TextBox)di.FindControl("txt_FirstName")).Text+",LastName:"+((TextBox)di.FindControl("txt_LastName")).Text+"<br>");
}
((TextBox)di.FindControl("txt_FirstName")).Visible=false;
((TextBox)di.FindControl("txt_LastName")).Visible=false;
((Label)di.FindControl("lab_FirstName")).Visible=true;
((Label)di.FindControl("lab_LastName")).Visible=true;
((CheckBox)di.FindControl("chkExport")).Checked=false;
}
}
}
}
}
Feedback
回复 引用 查看
回复 引用 查看
<%@ Page language="c#" Codebehind="WebForm5.aspx.cs" AutoEventWireup="false" Inherits="WebApplication1.WebForm5" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>WebForm5</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>
<body MS_POSITIONING="GridLayout">
<form id="Form1" method="post" runat="server">
<FONT face="新細明體">
<asp:Button id="Button1" style="Z-INDEX: 101; LEFT: 16px; POSITION: absolute; TOP: 24px" runat="server"
Text="New"></asp:Button>
<asp:Button id="Button2" style="Z-INDEX: 102; LEFT: 16px; POSITION: absolute; TOP: 64px" runat="server"
Text="Update"></asp:Button>
<asp:Button id="Button3" style="Z-INDEX: 103; LEFT: 16px; POSITION: absolute; TOP: 112px" runat="server"
Text="Save"></asp:Button></FONT>
</form>
</body>
</HTML>
回复 引用 查看
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace WebApplication1
{
/// <summary>
/// Summary description for WebForm5.
/// </summary>
public class WebForm5 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Button Button1;
protected System.Web.UI.WebControls.Button Button2;
protected System.Web.UI.WebControls.Button Button3;
private DataGrid _objDg = new DataGrid () ;
private string _eventName = "" ;
private void Page_Load(object sender, System.EventArgs e)
{
createDataGrid() ;
if (!this.IsPostBack)
createViewState() ;
else
{
if (ViewState["ButtonAction"] != null)
{
switch(ViewState["ButtonAction"].ToString().ToUpper ())
{
case "NEW":
createNewState() ;
break ;
case "UPDATE":
createEditState() ;
break ;
}
}
}
// Put user code to initialize the page here
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.Button1.Click += new System.EventHandler(this.Button1_Click);
this.Button2.Click += new System.EventHandler(this.Button2_Click);
this.Button3.Click += new System.EventHandler(this.Button3_Click);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
class TextBoxTemplate : ITemplate
{
private string column ;
public TextBoxTemplate(string f_column)
{
this.column = f_column ;
}
#region ITemplate Members
public void InstantiateIn(Control container)
{
// TODO: Add TextBoxTemplate.InstantiateIn implementation
TextBox objbox = new TextBox () ;
objbox.DataBinding +=new EventHandler(objbox_DataBinding);
container.Controls.Add (objbox) ;
}
#endregion
private void objbox_DataBinding(object sender, EventArgs e)
{
TextBox tb = (TextBox) sender;
DataGridItem container = (DataGridItem)tb.NamingContainer;
tb.Text = ((DataRowView) container.DataItem)[column].ToString();
}
}
class LabelTemplate:ITemplate
{
#region ITemplate Members
public void InstantiateIn(Control container)
{
// TODO: Add LabelTemplate.InstantiateIn implementation
Label objlbl = new Label() ;
objlbl.DataBinding +=new EventHandler(objlbl_DataBinding);
container.Controls.Add (objlbl) ;
}
#endregion
private void objlbl_DataBinding(object sender, EventArgs e)
{
Label objlbl = (Label)sender ;
DataGridItem container = (DataGridItem)objlbl.NamingContainer;
objlbl.Text = Convert.ToString(container.ItemIndex + 1) ;
}
}
class CheckBoxTemplate:ITemplate
{
#region ITemplate Members
public void InstantiateIn(Control container)
{
CheckBox objchk = new CheckBox() ;
container.Controls.Add (objchk) ;
}
#endregion
}
private void createViewState()
{
if (_objDg == null)
return ;
_objDg.DataSource = CreateDataSource() ;
_objDg.DataBind () ;
}
private void createNewState()
{
_objDg.DataSource = createNewDataSource() ;
_objDg.EditItemIndex = 0 ;
_objDg.DataBind () ;
}
private void createDataGrid()
{
if (_objDg == null)
_objDg = new DataGrid () ;
_objDg.Attributes.Add ("align","center") ;
TemplateColumn tm = new TemplateColumn() ;
LabelTemplate myTemp = new LabelTemplate() ;
tm.ItemTemplate = myTemp ;
_objDg.Columns.Add (tm) ;
tm = new TemplateColumn() ;
CheckBoxTemplate myTemp1 = new CheckBoxTemplate () ;
tm.ItemTemplate = myTemp1 ;
_objDg.Columns.Add (tm) ;
_objDg.EnableViewState = true ;
_objDg.AutoGenerateColumns = true ;
this.FindControl ("Form1").Controls.Add (_objDg) ;
}
回复 引用 查看
protected ICollection CreateDataSource()
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add(new DataColumn("IntegerValue", typeof(Int32)));
dt.Columns.Add(new DataColumn("StringValue", typeof(string)));
dt.Columns.Add(new DataColumn("CurrencyValue", typeof(double)));
for (int i = 0; i < 19; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = "Item " + i.ToString();
dr[2] = 1.23 * (i + 1);
dt.Rows.Add(dr);
}
DataView dv = new DataView(dt);
return dv;
}
private ICollection createNewDataSource()
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add(new DataColumn("IntegerValue", typeof(Int32)));
dt.Columns.Add(new DataColumn("StringValue", typeof(string)));
dt.Columns.Add(new DataColumn("CurrencyValue", typeof(double)));
dr = dt.NewRow () ;
dt.Rows.InsertAt(dr,0) ;
DataView dv = new DataView(dt);
return dv;
}
private void createEditState()
{
TemplateColumn tm = new TemplateColumn() ;
TextBoxTemplate myTemp = new TextBoxTemplate("IntegerValue") ;
tm.ItemTemplate = myTemp ;
_objDg.Columns.Add (tm) ;
tm = new TemplateColumn() ;
myTemp = new TextBoxTemplate ("StringValue") ;
tm.ItemTemplate = myTemp ;
_objDg.Columns.Add (tm) ;
_objDg.AutoGenerateColumns = false ;
_objDg.ItemDataBound +=new DataGridItemEventHandler(_objDg_ItemDataBound);
_objDg.DataSource = CreateDataSource() ;
_objDg.DataBind () ;
}
private void Button1_Click(object sender, System.EventArgs e)
{
ViewState["ButtonAction"] = "New" ;
}
private void Button2_Click(object sender, System.EventArgs e)
{
ViewState["ButtonAction"] = "Update" ;
createEditState() ;
}
private void _objDg_ItemDataBound(object sender, DataGridItemEventArgs e)
{
if((e.Item.ItemType==ListItemType.Item ) || (e.Item.ItemType==ListItemType.AlternatingItem))
{
for (int i = 2; i < e.Item.Cells.Count ; i ++)
{
//((TextBox)e.Item.Cells[i].Controls [0]).Attributes.Add ("onmouseover", "this.select()") ;
((TextBox)e.Item.Cells[i].Controls [0]).Attributes["onmouseover"] = "javascript:this.select()" ;
}
}
}
private void Button3_Click(object sender, System.EventArgs e)
{
string atr = "abc" ;
}
protected override void RaisePostBackEvent(IPostBackEventHandler sourceControl, string eventArgument)
{
_eventName = sourceControl.ToString () ;
base.RaisePostBackEvent (sourceControl, eventArgument);
}
}
}
在private void Button3_Click(object sender, System.EventArgs e)
設置斷點﹐當用戶按上:Update按鈕時﹐在服務器端無法得到DG中的任何值
回复 引用 查看
回复 引用 查看
回复 引用 查看
根本就不会等于true
回复 引用 查看
你忘记判断该页是否回传了。加上
if(!IsPostBack)
{
SetBind();
}
回复 引用 查看
其次,我要说,他妈的,其它网站就知道你妈的转载,转你娘呀,搜了一下午,全他妈的都是千篇一律的东西,你们他妈的就不会像这个网站一样,有点创新吗,你们转载的,真你妈的垃圾,C你们转栽亲妈的。
回复 引用 查看
回复 引用 查看