//
目前功能:排序、单选项、复选项、合并单元格、产生序列号、联动下拉框、编辑、删除、超连接、鼠标移动改变颜色、奇偶项颜色区分等
1.html代码
1.html代码
<
HTML
>
< HEAD >
< title > DatagridTest </ title >
< meta content ="Microsoft Visual Studio .NET 7.1" name ="GENERATOR" >
< meta content ="C#" name ="CODE_LANGUAGE" >
< meta content ="JavaScript" name ="vs_defaultClientScript" >
< meta content ="http://schemas.microsoft.com/intellisense/ie5" name ="vs_targetSchema" >
< script language ="javascript" >
function fun_option(obj)
{
document.Form1.hiduserid.value=obj.value;
}
function chkAll_true()
{
var chkall= document.all["chkAll"];
var chkother= document.all["chkExport"];
if(chkother.length>0)
{
for (var i=0;i<chkother.length;i++)
{
if(chkall.checked==true)
{
chkother[i].checked=true;
}
else
{
chkother[i].checked=false;
}
}
}
}
function Delete()
{
//debugger;
var chkother= document.all["chkExport"];
var temp="";
if(chkother.length>0)
{
for (var i=0;i<chkother.length;i++)
{
if(chkother[i].checked=true)
{
temp+=","+chkother[i].value;
}
}
temp=temp.substring(1,temp.length);
}
if (temp == "")
{
alert('You need to select a row in the list before selecting Delete./r/nPlease select a row and try again.');
}
else if (window.confirm("Are you sure to delete all these?"))
{
document.Form1.hiduserid.value=temp;
var deleteID='<%=btndelete.ClientID%>';
window.document.all(deleteID).click();
}
event.cancelBubble=true;
}
</ script >
</ HEAD >
< body >
< form id ="Form1" method ="post" runat ="server" >
< TABLE id ="Table1" height ="100%" cellSpacing ="1" cellPadding ="1" width ="100%" border ="1" >
< tr height ="30" >
< td >< INPUT id ="chkAll" onclick ="chkAll_true()" type ="checkbox" > 全选/取消 < asp:button id ="btndelete" runat ="server" Text ="删除" ></ asp:button ></ td >
</ tr >
< TR vAlign ="top" >
< TD width ="100%" colSpan ="5" >< asp:datagrid id ="DataGrid1" runat ="server" OnEditCommand ="Edit" OnCancelCommand ="Cancel" OnUpdateCommand ="Update"
DataKeyField ="UserID" AutoGenerateColumns ="False" AllowSorting ="True" BorderColor ="Tan" BorderWidth ="1px" BackColor ="LightGoldenrodYellow"
CellPadding ="2" GridLines ="None" ForeColor ="Black" OnDeleteCommand ="Delete" >
< FooterStyle BackColor ="Tan" ></ FooterStyle >
< SelectedItemStyle ForeColor ="GhostWhite" BackColor ="DarkSlateBlue" ></ SelectedItemStyle >
< AlternatingItemStyle BackColor ="PaleGoldenrod" ></ AlternatingItemStyle >
< HeaderStyle Font-Bold ="True" BackColor ="Tan" ></ HeaderStyle >
< Columns >
< asp:TemplateColumn HeaderText ="序号" >
< ItemTemplate >
< INPUT id =radio onclick =fun_option(this) type =radio value ='<%# DataBinder.Eval(Container.DataItem,"UserID") % > ' name=radio>
</ ItemTemplate >
< FooterTemplate >
</ FooterTemplate >
</ asp:TemplateColumn >
< asp:TemplateColumn HeaderText ="序号" >
< FooterTemplate >
</ FooterTemplate >
</ asp:TemplateColumn >
< asp:TemplateColumn >
< ItemTemplate >
< INPUT id ="chkExport" type ="checkbox" value ='<%# DataBinder.Eval(Container.DataItem,"UserID") % > '>
</ ItemTemplate >
</ asp:TemplateColumn >
< asp:BoundColumn DataField ="UserID" SortExpression ="UserID" ReadOnly ="True" HeaderText ="UserID" ></ asp:BoundColumn >
< asp:TemplateColumn SortExpression ="UserName" HeaderText ="姓名" >
< ItemTemplate >
< a href ="http://singlepine.cnblogs.com/articles/266538.html" target ="_blank" >
<% # DataBinder.Eval(Container.DataItem,"UserName") %>
</ a >
</ ItemTemplate >
< EditItemTemplate >
< asp:TextBox id =UserName Text ='<%# DataBinder.Eval(Container.DataItem,"UserName") % > ' Width="88px" Runat="server">
</ asp:TextBox >
</ EditItemTemplate >
</ asp:TemplateColumn >
< asp:TemplateColumn SortExpression ="province" HeaderText ="省市" >
< ItemTemplate >
<% # DataBinder.Eval(Container.DataItem,"province") %>
</ ItemTemplate >
< EditItemTemplate >
< asp:DropDownList id ="province" Runat ="server" AutoPostBack ="True" OnSelectedIndexChanged ="ddlpovince_SelectedIndexChanged" ></ asp:DropDownList >
</ EditItemTemplate >
</ asp:TemplateColumn >
< asp:TemplateColumn SortExpression ="city" HeaderText ="县市" >
< ItemTemplate >
<% # DataBinder.Eval(Container.DataItem,"city") %>
</ ItemTemplate >
< EditItemTemplate >
< asp:DropDownList id ="city" Runat ="server" ></ asp:DropDownList >
</ EditItemTemplate >
</ asp:TemplateColumn >
< asp:TemplateColumn SortExpression ="Enabled" HeaderText ="可见否" >
< ItemTemplate >
<% # DataBinder.Eval(Container.DataItem,"Enabled") %>
</ ItemTemplate >
< EditItemTemplate >
< asp:CheckBox id =chkenabled Runat ="server" Checked ='<%# DataBinder.Eval(Container.DataItem,"Enabled") % > '>
</ asp:CheckBox >
</ EditItemTemplate >
</ asp:TemplateColumn >
< asp:EditCommandColumn ButtonType ="PushButton" UpdateText ="更新" HeaderText ="编辑" CancelText ="取消" EditText ="编辑" ></ asp:EditCommandColumn >
< asp:ButtonColumn Text ="删除" ButtonType ="PushButton" HeaderText ="删除" CommandName ="Delete" ></ asp:ButtonColumn >
</ Columns >
< PagerStyle NextPageText ="下一页" PrevPageText ="上一页" HorizontalAlign ="Right" ForeColor ="DarkSlateBlue"
BackColor ="PaleGoldenrod" ></ PagerStyle >
</ asp:datagrid ></ TD >
</ TR >
< tr height ="30" >
< td ></ td >
</ tr >
</ TABLE >
< INPUT id ="hiduserid" type ="hidden" runat ="server" >
</ form >
</ body >
</ HTML >
2.cs代码
< HEAD >
< title > DatagridTest </ title >
< meta content ="Microsoft Visual Studio .NET 7.1" name ="GENERATOR" >
< meta content ="C#" name ="CODE_LANGUAGE" >
< meta content ="JavaScript" name ="vs_defaultClientScript" >
< meta content ="http://schemas.microsoft.com/intellisense/ie5" name ="vs_targetSchema" >
< script language ="javascript" >
function fun_option(obj)
{
document.Form1.hiduserid.value=obj.value;
}
function chkAll_true()
{
var chkall= document.all["chkAll"];
var chkother= document.all["chkExport"];
if(chkother.length>0)
{
for (var i=0;i<chkother.length;i++)
{
if(chkall.checked==true)
{
chkother[i].checked=true;
}
else
{
chkother[i].checked=false;
}
}
}
}
function Delete()
{
//debugger;
var chkother= document.all["chkExport"];
var temp="";
if(chkother.length>0)
{
for (var i=0;i<chkother.length;i++)
{
if(chkother[i].checked=true)
{
temp+=","+chkother[i].value;
}
}
temp=temp.substring(1,temp.length);
}
if (temp == "")
{
alert('You need to select a row in the list before selecting Delete./r/nPlease select a row and try again.');
}
else if (window.confirm("Are you sure to delete all these?"))
{
document.Form1.hiduserid.value=temp;
var deleteID='<%=btndelete.ClientID%>';
window.document.all(deleteID).click();
}
event.cancelBubble=true;
}
</ script >
</ HEAD >
< body >
< form id ="Form1" method ="post" runat ="server" >
< TABLE id ="Table1" height ="100%" cellSpacing ="1" cellPadding ="1" width ="100%" border ="1" >
< tr height ="30" >
< td >< INPUT id ="chkAll" onclick ="chkAll_true()" type ="checkbox" > 全选/取消 < asp:button id ="btndelete" runat ="server" Text ="删除" ></ asp:button ></ td >
</ tr >
< TR vAlign ="top" >
< TD width ="100%" colSpan ="5" >< asp:datagrid id ="DataGrid1" runat ="server" OnEditCommand ="Edit" OnCancelCommand ="Cancel" OnUpdateCommand ="Update"
DataKeyField ="UserID" AutoGenerateColumns ="False" AllowSorting ="True" BorderColor ="Tan" BorderWidth ="1px" BackColor ="LightGoldenrodYellow"
CellPadding ="2" GridLines ="None" ForeColor ="Black" OnDeleteCommand ="Delete" >
< FooterStyle BackColor ="Tan" ></ FooterStyle >
< SelectedItemStyle ForeColor ="GhostWhite" BackColor ="DarkSlateBlue" ></ SelectedItemStyle >
< AlternatingItemStyle BackColor ="PaleGoldenrod" ></ AlternatingItemStyle >
< HeaderStyle Font-Bold ="True" BackColor ="Tan" ></ HeaderStyle >
< Columns >
< asp:TemplateColumn HeaderText ="序号" >
< ItemTemplate >
< INPUT id =radio onclick =fun_option(this) type =radio value ='<%# DataBinder.Eval(Container.DataItem,"UserID") % > ' name=radio>
</ ItemTemplate >
< FooterTemplate >
</ FooterTemplate >
</ asp:TemplateColumn >
< asp:TemplateColumn HeaderText ="序号" >
< FooterTemplate >
</ FooterTemplate >
</ asp:TemplateColumn >
< asp:TemplateColumn >
< ItemTemplate >
< INPUT id ="chkExport" type ="checkbox" value ='<%# DataBinder.Eval(Container.DataItem,"UserID") % > '>
</ ItemTemplate >
</ asp:TemplateColumn >
< asp:BoundColumn DataField ="UserID" SortExpression ="UserID" ReadOnly ="True" HeaderText ="UserID" ></ asp:BoundColumn >
< asp:TemplateColumn SortExpression ="UserName" HeaderText ="姓名" >
< ItemTemplate >
< a href ="http://singlepine.cnblogs.com/articles/266538.html" target ="_blank" >
<% # DataBinder.Eval(Container.DataItem,"UserName") %>
</ a >
</ ItemTemplate >
< EditItemTemplate >
< asp:TextBox id =UserName Text ='<%# DataBinder.Eval(Container.DataItem,"UserName") % > ' Width="88px" Runat="server">
</ asp:TextBox >
</ EditItemTemplate >
</ asp:TemplateColumn >
< asp:TemplateColumn SortExpression ="province" HeaderText ="省市" >
< ItemTemplate >
<% # DataBinder.Eval(Container.DataItem,"province") %>
</ ItemTemplate >
< EditItemTemplate >
< asp:DropDownList id ="province" Runat ="server" AutoPostBack ="True" OnSelectedIndexChanged ="ddlpovince_SelectedIndexChanged" ></ asp:DropDownList >
</ EditItemTemplate >
</ asp:TemplateColumn >
< asp:TemplateColumn SortExpression ="city" HeaderText ="县市" >
< ItemTemplate >
<% # DataBinder.Eval(Container.DataItem,"city") %>
</ ItemTemplate >
< EditItemTemplate >
< asp:DropDownList id ="city" Runat ="server" ></ asp:DropDownList >
</ EditItemTemplate >
</ asp:TemplateColumn >
< asp:TemplateColumn SortExpression ="Enabled" HeaderText ="可见否" >
< ItemTemplate >
<% # DataBinder.Eval(Container.DataItem,"Enabled") %>
</ ItemTemplate >
< EditItemTemplate >
< asp:CheckBox id =chkenabled Runat ="server" Checked ='<%# DataBinder.Eval(Container.DataItem,"Enabled") % > '>
</ asp:CheckBox >
</ EditItemTemplate >
</ asp:TemplateColumn >
< asp:EditCommandColumn ButtonType ="PushButton" UpdateText ="更新" HeaderText ="编辑" CancelText ="取消" EditText ="编辑" ></ asp:EditCommandColumn >
< asp:ButtonColumn Text ="删除" ButtonType ="PushButton" HeaderText ="删除" CommandName ="Delete" ></ asp:ButtonColumn >
</ Columns >
< PagerStyle NextPageText ="下一页" PrevPageText ="上一页" HorizontalAlign ="Right" ForeColor ="DarkSlateBlue"
BackColor ="PaleGoldenrod" ></ PagerStyle >
</ asp:datagrid ></ TD >
</ TR >
< tr height ="30" >
< td ></ td >
</ tr >
</ TABLE >
< INPUT id ="hiduserid" type ="hidden" runat ="server" >
</ form >
</ body >
</ HTML >
public
class
DatagridTest : System.Web.UI.Page
{
protected System.Web.UI.WebControls.DataGrid DataGrid1;
protected System.Web.UI.HtmlControls.HtmlInputHidden hiduserid;
protected System.Web.UI.WebControls.Button btndelete;
private string constring="";
//目前功能:编辑、排序、单选项、复选项、合并单元格、产生序列号、联动下拉框、删除、超连接、鼠标移动改变颜色、奇偶项颜色区分
private void Page_Load(object sender, System.EventArgs e)
{
if(!Page.IsPostBack)
{
btndelete.Attributes.Add("onclick","Delete();");
SortExpression="";
sort="desc";
DataBind();
}
}
DataBind#region DataBind
private void DataBind()
{
string sql="select a.UserID,a.UserName,b.province,c.city,a.Enabled,b.provinceID,c.cityID from testgrid a ";
sql+=" left join povince b on a.Country=b.provinceID";
sql+=" left join city c on a.State=c.cityID";
DataSet ds=GetDataSet(sql);
dt=ds.Tables[0];
this.DataGrid1.DataSource=dt;
this.DataGrid1.DataBind();
}
#endregion
Web Form Designer generated code#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);
this.DataGrid1.ItemDataBound+=new DataGridItemEventHandler(DataGrid1_ItemDataBound);
this.DataGrid1.SortCommand+=new DataGridSortCommandEventHandler(DataGrid1_SortCommand);
this.DataGrid1.ItemCreated+=new DataGridItemEventHandler(DataGrid1_ItemCreated);
this.btndelete.Click += new System.EventHandler(this.btndelete_Click);
}
/**//// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
GetDataSet#region GetDataSet
private DataSet GetDataSet(string sql)
{
constring=System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"];
SqlDataAdapter sda =new SqlDataAdapter(sql,constring);
DataSet ds=new DataSet();
sda.Fill(ds);
return ds;
}
#endregion
DataGrid1_ItemDataBound#region DataGrid1_ItemDataBound
private void DataGrid1_ItemDataBound(object sender, DataGridItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
e.Item.Attributes.Add("ondblclick","alert('"+e.Item.Cells[3].Text+"');");
}
if (e.Item.ItemType!=ListItemType.Header)
{
if(e.Item.ItemIndex%2==0)
{
e.Item.Attributes.Add( "onmouseout","this.style.backgroundColor='PaleGoldenrod'");
}
else
{
e.Item.Attributes.Add( "onmouseout","this.style.backgroundColor='LightGoldenrodYellow'");
}
e.Item.Attributes.Add( "onmouseover","this.style.backgroundColor='#C1D2EE'");
e.Item.Cells[1].Text=Convert.ToString(e.Item.ItemIndex+1);//产生序号
}
if (e.Item.ItemType==ListItemType.Header)
{
e.Item.Cells[0].ColumnSpan=2;//合并单元格
e.Item.Cells[1].Visible=false;
}
string sqlpovince="select * from povince";
DataSet dspovince=GetDataSet(sqlpovince);
if(e.Item.ItemType==ListItemType.EditItem)
{
DropDownList ddlpovince=(DropDownList)e.Item.FindControl("province");
ddlpovince.DataSource=dspovince;
ddlpovince.DataTextField="province";
ddlpovince.DataValueField="provinceID";
ddlpovince.DataBind();
ddlpovince.Items.FindByValue(Convert.ToString(DataBinder.Eval(e.Item.DataItem,"provinceID"))).Selected=true;
if(e.Item.ItemType==ListItemType.EditItem)
{
if(ddlpovince.SelectedIndex!=-1)
{
string sqlcity="select * from city where father='"+ddlpovince.SelectedValue+"'";
DropDownList ddlcity=(DropDownList)e.Item.FindControl("city");
DataSet dscity=GetDataSet(sqlcity);
ddlcity.DataSource=dscity;
ddlcity.DataTextField="city";
ddlcity.DataValueField="cityID";
ddlcity.DataBind();
ddlcity.Items.FindByValue(Convert.ToString(DataBinder.Eval(e.Item.DataItem,"cityID"))).Selected=true;
}
}
}
}
#endregion
DataGrid1_SortCommand#region DataGrid1_SortCommand
private void DataGrid1_SortCommand(object source, DataGridSortCommandEventArgs e)
{
if(SortExpression==e.SortExpression.ToString())
{
if(sort=="asc")
{
sort="desc";
}
else
{
sort="asc";
}
}
else
{
if(sort=="asc")
{
sort="desc";
}
else
{
sort="asc";
}
}
SortExpression=e.SortExpression;
dt.DefaultView.Sort=e.SortExpression+" "+sort;
DataGrid1.DataSource=dt;
DataGrid1.DataBind();
}
#endregion
DataGrid1_ItemCreated#region DataGrid1_ItemCreated
private void DataGrid1_ItemCreated(object sender, DataGridItemEventArgs e)
{
for (int i=3; i < DataGrid1.Columns.Count-2; i++)//-2的意思是两个button列不用排序
{
if (i == 0) continue;
if(e.Item.ItemIndex==-1)
{
if (DataGrid1.Columns[i].SortExpression == SortExpression)
{
TableCell tableCell = e.Item.Cells[i];
Label label = new Label();
label.Font.Name = "webdings";
if(sort=="asc")
{
label.Text="6";
}
else
{
label.Text="5";
}
label.Width =20;
tableCell.Controls.Add(label);
}
}
}
foreach(DataGridItem di in this.DataGrid1.Items)
{
if(di.ItemType==ListItemType.Item||di.ItemType==ListItemType.AlternatingItem)
{
((Button)di.Cells[9].Controls[0]).Attributes.Add("onclick","return confirm('确认删除此项吗?');");
}
}
}
#endregion
property#region property
private DataTable dt
{
get
{
if(ViewState["dt"]!=null)
{
return (DataTable)ViewState["dt"];
}
else
{
return null;
}
}
set
{
ViewState["dt"]=value;
}
}
private string SortExpression
{
get
{
if(ViewState["SortExpression"]!=null && ViewState["SortExpression"].ToString()!=string.Empty)
{
return ViewState["SortExpression"].ToString();
}
else
{
return "";
}
}
set
{
ViewState["SortExpression"]=value;
}
}
private string sort
{
get
{
if(ViewState["sort"]!=null && ViewState["sort"].ToString()!=string.Empty)
{
return ViewState["sort"].ToString();
}
else
{
return "";
}
}
set
{
ViewState["sort"]=value;
}
}
#endregion
Edit#region Edit
protected void Edit(object sender,DataGridCommandEventArgs e)
{
this.DataGrid1.EditItemIndex=e.Item.ItemIndex;
DataBind();
}
#endregion
Cancel#region Cancel
protected void Cancel(object sender,DataGridCommandEventArgs e)
{
this.DataGrid1.EditItemIndex=-1;
DataBind();
}
#endregion
Update#region Update
protected void Update(object sender,DataGridCommandEventArgs e)
{
if(e.Item.ItemType==ListItemType.EditItem)
{
SqlConnection conn=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"]);
SqlCommand comm=new SqlCommand("update testgrid set UserName=@UserName,Country=@province,State=@city,Enabled=@Enabled where UserID=@UserID",conn);
SqlParameter parm1=new SqlParameter("@UserName",SqlDbType.NVarChar,50);
parm1.Value=((TextBox)e.Item.FindControl("UserName")).Text;
SqlParameter parm2=new SqlParameter("@province",SqlDbType.NVarChar,50);
parm2.Value=((DropDownList)e.Item.FindControl("province")).SelectedValue;
SqlParameter parm3=new SqlParameter("@city",SqlDbType.NVarChar,50);
parm3.Value=((DropDownList)e.Item.FindControl("city")).SelectedValue;
SqlParameter parm4=new SqlParameter("@Enabled",SqlDbType.Bit);
parm4.Value=((CheckBox)e.Item.FindControl("chkenabled")).Checked;
SqlParameter parm5=new SqlParameter("@UserID",SqlDbType.Int);
parm5.Value=this.DataGrid1.DataKeys[e.Item.ItemIndex];
comm.Parameters.Add(parm1);
comm.Parameters.Add(parm2);
comm.Parameters.Add(parm3);
comm.Parameters.Add(parm4);
comm.Parameters.Add(parm5);
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
this.DataGrid1.EditItemIndex=-1;
DataBind();
}
}
#endregion
Delete event#region Delete event
protected void Delete(object sender,DataGridCommandEventArgs e)
{
delete(this.DataGrid1.DataKeys[e.Item.ItemIndex].ToString());
}
#endregion
ddlpovince_SelectedIndexChanged#region ddlpovince_SelectedIndexChanged
public void ddlpovince_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddlpovince = sender as DropDownList;
if(ddlpovince.SelectedIndex!=-1)
{
DropDownList ddlcity = ((Control)(((Control)sender)).Parent).FindControl("city") as DropDownList;
string sqlcity="select * from city where father='"+ddlpovince.SelectedValue+"'";
DataSet dscity=GetDataSet(sqlcity);
ddlcity.DataSource=dscity;
ddlcity.DataTextField="city";
ddlcity.DataValueField="cityID";
ddlcity.DataBind();
}
}
#endregion
btndelete_Click#region btndelete_Click
private void btndelete_Click(object sender, System.EventArgs e)
{
string[] delid=this.hiduserid.Value.Split(',');
for(int m=0;m<delid.Length;m++)
{
delete(delid[m]);
}
}
#endregion
delete#region delete
private void delete(string id)
{
SqlConnection conn=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"]);
SqlCommand comm=new SqlCommand("delete from testgrid where UserID=@UserID",conn);
SqlParameter parm1=new SqlParameter("@UserID",SqlDbType.Int);
parm1.Value=Convert.ToInt32(id);
comm.Parameters.Add(parm1);
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
DataBind();
}
#endregion
}
3. 数据库教本(或下载真实数据
/Files/singlepine/area.rar)
{
protected System.Web.UI.WebControls.DataGrid DataGrid1;
protected System.Web.UI.HtmlControls.HtmlInputHidden hiduserid;
protected System.Web.UI.WebControls.Button btndelete;
private string constring="";
//目前功能:编辑、排序、单选项、复选项、合并单元格、产生序列号、联动下拉框、删除、超连接、鼠标移动改变颜色、奇偶项颜色区分
private void Page_Load(object sender, System.EventArgs e)
{
if(!Page.IsPostBack)
{
btndelete.Attributes.Add("onclick","Delete();");
SortExpression="";
sort="desc";
DataBind();
}
}
DataBind#region DataBind
private void DataBind()
{
string sql="select a.UserID,a.UserName,b.province,c.city,a.Enabled,b.provinceID,c.cityID from testgrid a ";
sql+=" left join povince b on a.Country=b.provinceID";
sql+=" left join city c on a.State=c.cityID";
DataSet ds=GetDataSet(sql);
dt=ds.Tables[0];
this.DataGrid1.DataSource=dt;
this.DataGrid1.DataBind();
}
#endregion
Web Form Designer generated code#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);
this.DataGrid1.ItemDataBound+=new DataGridItemEventHandler(DataGrid1_ItemDataBound);
this.DataGrid1.SortCommand+=new DataGridSortCommandEventHandler(DataGrid1_SortCommand);
this.DataGrid1.ItemCreated+=new DataGridItemEventHandler(DataGrid1_ItemCreated);
this.btndelete.Click += new System.EventHandler(this.btndelete_Click);
}
/**//// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
GetDataSet#region GetDataSet
private DataSet GetDataSet(string sql)
{
constring=System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"];
SqlDataAdapter sda =new SqlDataAdapter(sql,constring);
DataSet ds=new DataSet();
sda.Fill(ds);
return ds;
}
#endregion
DataGrid1_ItemDataBound#region DataGrid1_ItemDataBound
private void DataGrid1_ItemDataBound(object sender, DataGridItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
e.Item.Attributes.Add("ondblclick","alert('"+e.Item.Cells[3].Text+"');");
}
if (e.Item.ItemType!=ListItemType.Header)
{
if(e.Item.ItemIndex%2==0)
{
e.Item.Attributes.Add( "onmouseout","this.style.backgroundColor='PaleGoldenrod'");
}
else
{
e.Item.Attributes.Add( "onmouseout","this.style.backgroundColor='LightGoldenrodYellow'");
}
e.Item.Attributes.Add( "onmouseover","this.style.backgroundColor='#C1D2EE'");
e.Item.Cells[1].Text=Convert.ToString(e.Item.ItemIndex+1);//产生序号
}
if (e.Item.ItemType==ListItemType.Header)
{
e.Item.Cells[0].ColumnSpan=2;//合并单元格
e.Item.Cells[1].Visible=false;
}
string sqlpovince="select * from povince";
DataSet dspovince=GetDataSet(sqlpovince);
if(e.Item.ItemType==ListItemType.EditItem)
{
DropDownList ddlpovince=(DropDownList)e.Item.FindControl("province");
ddlpovince.DataSource=dspovince;
ddlpovince.DataTextField="province";
ddlpovince.DataValueField="provinceID";
ddlpovince.DataBind();
ddlpovince.Items.FindByValue(Convert.ToString(DataBinder.Eval(e.Item.DataItem,"provinceID"))).Selected=true;
if(e.Item.ItemType==ListItemType.EditItem)
{
if(ddlpovince.SelectedIndex!=-1)
{
string sqlcity="select * from city where father='"+ddlpovince.SelectedValue+"'";
DropDownList ddlcity=(DropDownList)e.Item.FindControl("city");
DataSet dscity=GetDataSet(sqlcity);
ddlcity.DataSource=dscity;
ddlcity.DataTextField="city";
ddlcity.DataValueField="cityID";
ddlcity.DataBind();
ddlcity.Items.FindByValue(Convert.ToString(DataBinder.Eval(e.Item.DataItem,"cityID"))).Selected=true;
}
}
}
}
#endregion
DataGrid1_SortCommand#region DataGrid1_SortCommand
private void DataGrid1_SortCommand(object source, DataGridSortCommandEventArgs e)
{
if(SortExpression==e.SortExpression.ToString())
{
if(sort=="asc")
{
sort="desc";
}
else
{
sort="asc";
}
}
else
{
if(sort=="asc")
{
sort="desc";
}
else
{
sort="asc";
}
}
SortExpression=e.SortExpression;
dt.DefaultView.Sort=e.SortExpression+" "+sort;
DataGrid1.DataSource=dt;
DataGrid1.DataBind();
}
#endregion
DataGrid1_ItemCreated#region DataGrid1_ItemCreated
private void DataGrid1_ItemCreated(object sender, DataGridItemEventArgs e)
{
for (int i=3; i < DataGrid1.Columns.Count-2; i++)//-2的意思是两个button列不用排序
{
if (i == 0) continue;
if(e.Item.ItemIndex==-1)
{
if (DataGrid1.Columns[i].SortExpression == SortExpression)
{
TableCell tableCell = e.Item.Cells[i];
Label label = new Label();
label.Font.Name = "webdings";
if(sort=="asc")
{
label.Text="6";
}
else
{
label.Text="5";
}
label.Width =20;
tableCell.Controls.Add(label);
}
}
}
foreach(DataGridItem di in this.DataGrid1.Items)
{
if(di.ItemType==ListItemType.Item||di.ItemType==ListItemType.AlternatingItem)
{
((Button)di.Cells[9].Controls[0]).Attributes.Add("onclick","return confirm('确认删除此项吗?');");
}
}
}
#endregion
property#region property
private DataTable dt
{
get
{
if(ViewState["dt"]!=null)
{
return (DataTable)ViewState["dt"];
}
else
{
return null;
}
}
set
{
ViewState["dt"]=value;
}
}
private string SortExpression
{
get
{
if(ViewState["SortExpression"]!=null && ViewState["SortExpression"].ToString()!=string.Empty)
{
return ViewState["SortExpression"].ToString();
}
else
{
return "";
}
}
set
{
ViewState["SortExpression"]=value;
}
}
private string sort
{
get
{
if(ViewState["sort"]!=null && ViewState["sort"].ToString()!=string.Empty)
{
return ViewState["sort"].ToString();
}
else
{
return "";
}
}
set
{
ViewState["sort"]=value;
}
}
#endregion
Edit#region Edit
protected void Edit(object sender,DataGridCommandEventArgs e)
{
this.DataGrid1.EditItemIndex=e.Item.ItemIndex;
DataBind();
}
#endregion
Cancel#region Cancel
protected void Cancel(object sender,DataGridCommandEventArgs e)
{
this.DataGrid1.EditItemIndex=-1;
DataBind();
}
#endregion
Update#region Update
protected void Update(object sender,DataGridCommandEventArgs e)
{
if(e.Item.ItemType==ListItemType.EditItem)
{
SqlConnection conn=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"]);
SqlCommand comm=new SqlCommand("update testgrid set UserName=@UserName,Country=@province,State=@city,Enabled=@Enabled where UserID=@UserID",conn);
SqlParameter parm1=new SqlParameter("@UserName",SqlDbType.NVarChar,50);
parm1.Value=((TextBox)e.Item.FindControl("UserName")).Text;
SqlParameter parm2=new SqlParameter("@province",SqlDbType.NVarChar,50);
parm2.Value=((DropDownList)e.Item.FindControl("province")).SelectedValue;
SqlParameter parm3=new SqlParameter("@city",SqlDbType.NVarChar,50);
parm3.Value=((DropDownList)e.Item.FindControl("city")).SelectedValue;
SqlParameter parm4=new SqlParameter("@Enabled",SqlDbType.Bit);
parm4.Value=((CheckBox)e.Item.FindControl("chkenabled")).Checked;
SqlParameter parm5=new SqlParameter("@UserID",SqlDbType.Int);
parm5.Value=this.DataGrid1.DataKeys[e.Item.ItemIndex];
comm.Parameters.Add(parm1);
comm.Parameters.Add(parm2);
comm.Parameters.Add(parm3);
comm.Parameters.Add(parm4);
comm.Parameters.Add(parm5);
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
this.DataGrid1.EditItemIndex=-1;
DataBind();
}
}
#endregion
Delete event#region Delete event
protected void Delete(object sender,DataGridCommandEventArgs e)
{
delete(this.DataGrid1.DataKeys[e.Item.ItemIndex].ToString());
}
#endregion
ddlpovince_SelectedIndexChanged#region ddlpovince_SelectedIndexChanged
public void ddlpovince_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddlpovince = sender as DropDownList;
if(ddlpovince.SelectedIndex!=-1)
{
DropDownList ddlcity = ((Control)(((Control)sender)).Parent).FindControl("city") as DropDownList;
string sqlcity="select * from city where father='"+ddlpovince.SelectedValue+"'";
DataSet dscity=GetDataSet(sqlcity);
ddlcity.DataSource=dscity;
ddlcity.DataTextField="city";
ddlcity.DataValueField="cityID";
ddlcity.DataBind();
}
}
#endregion
btndelete_Click#region btndelete_Click
private void btndelete_Click(object sender, System.EventArgs e)
{
string[] delid=this.hiduserid.Value.Split(',');
for(int m=0;m<delid.Length;m++)
{
delete(delid[m]);
}
}
#endregion
delete#region delete
private void delete(string id)
{
SqlConnection conn=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"]);
SqlCommand comm=new SqlCommand("delete from testgrid where UserID=@UserID",conn);
SqlParameter parm1=new SqlParameter("@UserID",SqlDbType.Int);
parm1.Value=Convert.ToInt32(id);
comm.Parameters.Add(parm1);
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
DataBind();
}
#endregion
}
if
exists
(
select
*
from
dbo.sysobjects
where
id
=
object_id
(N
'
[dbo].[TestGrid]
'
)
and
OBJECTPROPERTY
(id, N
'
IsUserTable
'
)
=
1
)
drop table [ dbo ] . [ TestGrid ]
GO
if exists ( select * from dbo.sysobjects where id = object_id (N ' [dbo].[city] ' ) and OBJECTPROPERTY (id, N ' IsUserTable ' ) = 1 )
drop table [ dbo ] . [ city ]
GO
if exists ( select * from dbo.sysobjects where id = object_id (N ' [dbo].[povince] ' ) and OBJECTPROPERTY (id, N ' IsUserTable ' ) = 1 )
drop table [ dbo ] . [ povince ]
GO
CREATE TABLE [ dbo ] . [ TestGrid ] (
[ UserID ] [ int ] NOT NULL ,
[ UserName ] [ nvarchar ] ( 50 ) COLLATE Chinese_PRC_CI_AS NULL ,
[ Country ] [ nvarchar ] ( 50 ) COLLATE Chinese_PRC_CI_AS NULL ,
[ State ] [ nvarchar ] ( 50 ) COLLATE Chinese_PRC_CI_AS NULL ,
[ Enabled ] [ bit ] NULL
) ON [ PRIMARY ]
GO
CREATE TABLE [ dbo ] . [ city ] (
[ id ] [ int ] NOT NULL ,
[ cityID ] [ nvarchar ] ( 6 ) COLLATE Chinese_PRC_CI_AS NULL ,
[ city ] [ nvarchar ] ( 50 ) COLLATE Chinese_PRC_CI_AS NULL ,
[ father ] [ nvarchar ] ( 6 ) COLLATE Chinese_PRC_CI_AS NULL
) ON [ PRIMARY ]
GO
CREATE TABLE [ dbo ] . [ povince ] (
[ id ] [ int ] NOT NULL ,
[ provinceID ] [ nvarchar ] ( 6 ) COLLATE Chinese_PRC_CI_AS NULL ,
[ province ] [ nvarchar ] ( 40 ) COLLATE Chinese_PRC_CI_AS NULL
) ON [ PRIMARY ]
GO
drop table [ dbo ] . [ TestGrid ]
GO
if exists ( select * from dbo.sysobjects where id = object_id (N ' [dbo].[city] ' ) and OBJECTPROPERTY (id, N ' IsUserTable ' ) = 1 )
drop table [ dbo ] . [ city ]
GO
if exists ( select * from dbo.sysobjects where id = object_id (N ' [dbo].[povince] ' ) and OBJECTPROPERTY (id, N ' IsUserTable ' ) = 1 )
drop table [ dbo ] . [ povince ]
GO
CREATE TABLE [ dbo ] . [ TestGrid ] (
[ UserID ] [ int ] NOT NULL ,
[ UserName ] [ nvarchar ] ( 50 ) COLLATE Chinese_PRC_CI_AS NULL ,
[ Country ] [ nvarchar ] ( 50 ) COLLATE Chinese_PRC_CI_AS NULL ,
[ State ] [ nvarchar ] ( 50 ) COLLATE Chinese_PRC_CI_AS NULL ,
[ Enabled ] [ bit ] NULL
) ON [ PRIMARY ]
GO
CREATE TABLE [ dbo ] . [ city ] (
[ id ] [ int ] NOT NULL ,
[ cityID ] [ nvarchar ] ( 6 ) COLLATE Chinese_PRC_CI_AS NULL ,
[ city ] [ nvarchar ] ( 50 ) COLLATE Chinese_PRC_CI_AS NULL ,
[ father ] [ nvarchar ] ( 6 ) COLLATE Chinese_PRC_CI_AS NULL
) ON [ PRIMARY ]
GO
CREATE TABLE [ dbo ] . [ povince ] (
[ id ] [ int ] NOT NULL ,
[ provinceID ] [ nvarchar ] ( 6 ) COLLATE Chinese_PRC_CI_AS NULL ,
[ province ] [ nvarchar ] ( 40 ) COLLATE Chinese_PRC_CI_AS NULL
) ON [ PRIMARY ]
GO