smhy8187

 

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>

后台:

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;
                }
            }
        }
    }
}


 

posted on 2005-07-15 15:57 lovecherry 阅读(4442) 评论(11)  编辑  收藏 所属分类: webform

Feedback

#1楼 61.235.98.* 2005-08-12 12:49 過客 [未注册用户]
如果DataGrid1是動態創建如果寫呢?我發現如果動態的話﹐當客戶點擊"更新"的時候﹐服務器端無法得到客戶端的數據?這是為什么?
  回复  引用  查看    

#2楼 [楼主] 2005-08-12 14:16 lovecherry
楼上:http://www.cnblogs.com/lovecherry/archive/2005/03/26/126102.html
  回复  引用  查看    

#3楼 61.235.98.* 2005-08-15 10:48 過客 [未注册用户]
前台﹕
<%@ 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>




  回复  引用  查看    

#4楼 61.235.98.* 2005-08-15 10:49 過客 [未注册用户]
后台﹕
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) ;
}

  回复  引用  查看    

#5楼 61.235.98.* 2005-08-15 10:49 過客 [未注册用户]

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中的任何值
  回复  引用  查看    

#6楼 202.194.158.* 2006-05-20 11:33 zk [未注册用户]
您好,版主,我刚刚开始学asp.net,所以懂得不多,我按照你的思路对动态的进行了尝试,在vs2005中,出现了许多错误,我改了改,改不下去,这个文件是什么运行环境呢?我应该怎样做呢?
  回复  引用  查看    

#7楼 211.95.122.* 2006-06-15 10:24 lian_feng [未注册用户]
看了上面的内容,想请问一下,如果我做的是一个分页的有CHECKBOX的DATAGRID,是否只能一页一页的保存,因为每次从DATAGRID里面读取的数据只能是当前页面的,请问有什么办法可以一次保存所有的数据?
  回复  引用  查看    

#8楼 60.63.64.* 2006-09-13 15:16 jiangtiangming [未注册用户]
运行至((CheckBox)di.FindControl("chkExport")).Checked
根本就不会等于true
  回复  引用  查看    

#9楼 211.147.247.* 2006-10-06 10:11 Boniz [未注册用户]
@jiangtiangming

你忘记判断该页是否回传了。加上
if(!IsPostBack)
{
SetBind();
}

  回复  引用  查看    

#10楼 218.12.56.* 2007-04-20 16:30 水星 [未注册用户]
首先感谢楼主的,在次,找了这么久终于找到这个有用的东西了,真难啊。
其次,我要说,他妈的,其它网站就知道你妈的转载,转你娘呀,搜了一下午,全他妈的都是千篇一律的东西,你们他妈的就不会像这个网站一样,有点创新吗,你们转载的,真你妈的垃圾,C你们转栽亲妈的。
  回复  引用  查看    

#11楼 202.100.200.* 2007-09-04 09:00 zzx [未注册用户]
回(楼上)^5 这个应该是vs2003吧~~~
  回复  引用  查看    

posted on 2007-10-19 13:51  new2008  阅读(857)  评论(0编辑  收藏  举报

导航