DataGrid实现增删(带提示)改和分页

<%@ Page language="c#" Codebehind="WebForm5.aspx.cs" AutoEventWireup="false" Inherits="csdn.WebForm5"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
    
<HEAD>
        
<title>WebForm5</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">
    
</HEAD>
    
<body>
        
<form id="Form1" method="post" runat="server">
            
<input type="hidden" id="rd" runat="server" name="rd">
            
<asp:textbox id="TextBox1" runat="server" Width="88px"></asp:textbox>
            
<asp:TextBox id="TextBox2" runat="server" Width="40px"></asp:TextBox>
            
<asp:Button id="Button1" runat="server" Text="添加"></asp:Button>
            
<asp:TextBox id="TextBox3" runat="server" Width="128px"></asp:TextBox>
            
<asp:Button id="Button2" runat="server" Text="筛选"></asp:Button>
            
<asp:Button id="Button3" runat="server" Text="下载"></asp:Button>
            
<asp:DataGrid ID="DataGrid1" runat="server" AutoGenerateColumns="False" DataKeyField="ID" AllowPaging="True"
                PageSize
="20" OnEditCommand="edit" OnCancelCommand="cancel" OnUpdateCommand="update">
              
<columns>
              
<asp:TemplateColumn HeaderText="多选">
                
<itemtemplate>
                  
<input type="hidden" id="SelectedID" runat="server" 
                value
='<%# Container.ItemIndex%>'  name="SelectedID"/>
                  
<asp:CheckBox ID="chkExport" runat="server" />            
    
</itemtemplate>
              
</asp:TemplateColumn>
              
<asp:TemplateColumn HeaderText="单选">
                
<itemtemplate>
                  
<%# Container.ItemIndex+1%>
                  
<input type=radio name="rad" value='<%# Container.ItemIndex+1%>'>
                
</itemtemplate>
              
</asp:TemplateColumn>
              
<asp:TemplateColumn HeaderText="姓名">
                
<itemtemplate>
                  
<%# myfunc(DataBinder.Eval(Container.DataItem,"vName")) %>
                
</itemtemplate>
                
<edititemtemplate>
                  
<asp:TextBox ID="name" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"vName") %>' Width="88px"> </asp:TextBox>
                
</edititemtemplate>
              
</asp:TemplateColumn>
              
<asp:TemplateColumn HeaderText="年龄">
                
<itemtemplate>
                  
<%# DataBinder.Eval(Container.DataItem,"iAge"%>
                
</itemtemplate>
                
<edititemtemplate>
                  
<asp:TextBox ID="age" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"iAge") %>' Width="40px"> </asp:TextBox>
                
</edititemtemplate>
              
</asp:TemplateColumn>
              
<asp:TemplateColumn HeaderText="打开">
                
<itemtemplate>
                  
<asp:HyperLink Text="打开" NavigateUrl='<%#"newpage.aspx?name="+DataBinder.Eval(Container.DataItem, "vname")+"&age="+DataBinder.Eval(Container.DataItem, "iage") %>' runat="server" Target="_blank"> </asp:HyperLink>
                
</itemtemplate>
              
</asp:TemplateColumn>
              
<asp:TemplateColumn HeaderText="打开">
                
<itemtemplate>
                  
<asp:HyperLink Text="打开" NavigateUrl='<%# myfunc2(DataBinder.Eval(Container.DataItem,"vName"),DataBinder.Eval(Container.DataItem,"iAge"))%> ' runat="server" Target="_blank" ID="Hyperlink1"> </asp:HyperLink>
                
</itemtemplate>
              
</asp:TemplateColumn>
              
<asp:EditCommandColumn ButtonType="LinkButton" UpdateText="更新" CancelText="取消" EditText="编辑"></asp:EditCommandColumn>
              
<asp:ButtonColumn Text="删除" CommandName="del"></asp:ButtonColumn>
              
</columns>
              
<pagerstyle Mode="NumericPages"></pagerstyle>
            
</asp:DataGrid>            
          
<asp:Label id="Label1" runat="server"></asp:Label>
          
<asp:Button ID="button4" runat="server" Text="单选结果"></asp:Button>            
          
<asp:Button id="Button5" runat="server" Text="多选结果"></asp:Button>
            
<asp:Button id="Button6" runat="server" Text="选中所有"></asp:Button>
            
<asp:Button id="Button7" runat="server" Text="取消所有"></asp:Button></form>
        
<p>&nbsp;</p>
        
<p>&nbsp;</p>
    
</body>
</HTML>
后台代码:
// C# Document
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; using System.IO;

namespace csdn
{
    
/**//// <summary>
    
/// WebForm5 的摘要说明。
    
/// </summary>

    public class WebForm5 : System.Web.UI.Page
    
{
        
protected System.Web.UI.WebControls.TextBox TextBox1;
        
protected System.Web.UI.WebControls.TextBox TextBox2;
        
protected System.Web.UI.WebControls.Button Button1;
        
protected System.Web.UI.WebControls.TextBox TextBox3;
        
protected System.Web.UI.WebControls.Button Button2;
        
protected System.Web.UI.WebControls.Button Button3;
        
protected System.Web.UI.WebControls.Label Label1;
        
protected System.Web.UI.HtmlControls.HtmlInputHidden rd;
        
protected System.Web.UI.WebControls.Button button4;
        
protected System.Web.UI.WebControls.Button Button5;
        
protected System.Web.UI.WebControls.Button Button6;
        
protected System.Web.UI.WebControls.DataGrid DataGrid1;
        
protected System.Web.UI.WebControls.Button Button7;    
    
        
private void Page_Load(object sender, System.EventArgs e)
        
{

            
string js = "";
            js
+="<script>\r\n";
            js
+="function ld(){\r\n";
            js
+="for(i=0;i<document.getElementsByName('rad').length;i++)\r\n";
            js
+="if(document.getElementsByName('rad')[i].value==";
            js
+="document.getElementById('rd').value) ";
            js
+="document.getElementsByName('rad')[i].checked=true\r\n";
            js
+="}\r\n";
            js
+="window.onload=ld\r\n";
            js
+="</script>\r\n";
            
this.RegisterClientScriptBlock("js",js);

            
if(!IsPostBack)
            
{
                SetBind();
            }

            
        }


        
protected void SetBind()
        
{

            SqlConnection conn
=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["conn"]);
            SqlDataAdapter da
=new SqlDataAdapter("select * from tb1",conn);
            DataSet ds
=new DataSet();
            da.Fill(ds,
"table1");
            
this.DataGrid1.DataSource=ds.Tables["table1"];
            
this.DataGrid1.DataBind();
            
this.Label1.Text=ds.Tables["table1"].Compute("avg(iAge)","iAge>20").ToString();
        }


        
protected void SetBind(string s)
        
{
            SqlConnection conn
=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["conn"]);
            SqlDataAdapter da
=new SqlDataAdapter("select * from tb1",conn);
            DataSet ds
=new DataSet();
            da.Fill(ds,
"table1");
            DataView dv
=ds.Tables["table1"].DefaultView;
            dv.RowFilter
=s;
            
this.DataGrid1.DataSource=dv;
            
this.DataGrid1.DataBind();
        }


        Web 窗体设计器生成的代码
Web 窗体设计器生成的代码

        
private void Button1_Click(object sender, System.EventArgs e)
        
{
            SqlConnection conn
=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["conn"]);
            SqlCommand comm
=new SqlCommand("insert into tb1 (vName,iAge) values (@vName,@iAge)",conn);
            SqlParameter parm1
=new SqlParameter("@vName",SqlDbType.NVarChar,50);
            parm1.Value
=this.TextBox1.Text;
            SqlParameter parm2
=new SqlParameter("@iAge",SqlDbType.Int);
            parm2.Value
=this.TextBox2.Text;
            comm.Parameters.Add(parm1);
            comm.Parameters.Add(parm2);
            conn.Open();
            comm.ExecuteNonQuery();
            conn.Close();
            SetBind();
        }


        
private void DataGrid1_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
        
{
            
if(e.CommandName=="del"&&e.Item.ItemType!=ListItemType.EditItem)
            
{
                SqlConnection conn
=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["conn"]);
                SqlCommand comm
=new SqlCommand("delete from tb1 where ID=@id",conn);
                SqlParameter parm1
=new SqlParameter("@id",SqlDbType.Int);
                parm1.Value
=this.DataGrid1.DataKeys[e.Item.ItemIndex];
                comm.Parameters.Add(parm1);
                conn.Open();
                comm.ExecuteNonQuery();
                conn.Close();
                SetBind();
            }

        }


        
private void DataGrid1_PageIndexChanged(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
        
{
            
this.DataGrid1.CurrentPageIndex=e.NewPageIndex;
            SetBind();
        }


        
protected void edit(object sender,DataGridCommandEventArgs e)
        
{
            
this.DataGrid1.EditItemIndex=e.Item.ItemIndex;
            SetBind();
        }


        
protected void cancel(object sender,DataGridCommandEventArgs e)
        
{
            
this.DataGrid1.EditItemIndex=-1;
            SetBind();
        }


        
protected void update(object sender,DataGridCommandEventArgs e)
        
{
            
if(e.Item.ItemType==ListItemType.EditItem)
            
{
                SqlConnection conn
=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["conn"]);
                SqlCommand comm
=new SqlCommand("update tb1 set vName=@vName,iAge=@iAge where ID=@id",conn);
                SqlParameter parm1
=new SqlParameter("@vName",SqlDbType.NVarChar,50);
                parm1.Value
=((TextBox)e.Item.FindControl("name")).Text;
                SqlParameter parm2
=new SqlParameter("@iAge",SqlDbType.Int);
                parm2.Value
=((TextBox)e.Item.FindControl("age")).Text;
                SqlParameter parm3
=new SqlParameter("@id",SqlDbType.Int);
                parm3.Value
=this.DataGrid1.DataKeys[e.Item.ItemIndex];
                comm.Parameters.Add(parm1);
                comm.Parameters.Add(parm2);
                comm.Parameters.Add(parm3);
                conn.Open();
                comm.ExecuteNonQuery();
                conn.Close();
                
this.DataGrid1.EditItemIndex=-1;
                SetBind();
            }

        }


        
private void DataGrid1_ItemCreated(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
        
{
            
                
if(e.Item.ItemType==ListItemType.Item||e.Item.ItemType==ListItemType.AlternatingItem||e.Item.ItemType==ListItemType.EditItem)
                
{
                    ((LinkButton)e.Item.Cells[
7].Controls[0]).Attributes.Add("onclick","return confirm('delete?');");
                }

            
        }


        
private void Button2_Click(object sender, System.EventArgs e)
        
{
            
if(this.TextBox3.Text=="")
            
{
                SetBind();
            }

            
else
            
{
                SetBind(
this.TextBox3.Text);
            }

        }


        
private void DataGrid1_SelectedIndexChanged(object sender, System.EventArgs e)
        
{
            
        }


        
private void Button3_Click(object sender, System.EventArgs e)
        
{
            SqlConnection conn
=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["conn"]);
            SqlDataAdapter da
=new SqlDataAdapter("select * from tb1",conn);
            DataSet ds
=new DataSet();
            da.Fill(ds,
"table1");
            DataTable dt
=ds.Tables["table1"];
            
string name=System.Configuration.ConfigurationSettings.AppSettings["downloadurl"].ToString()+DateTime.Today.ToString("yyyyMMdd")+new Random(DateTime.Now.Millisecond).Next(10000).ToString()+".csv";
            FileStream fs
=new FileStream(name,FileMode.Create,FileAccess.Write);
            StreamWriter sw
=new StreamWriter(fs,System.Text.Encoding.GetEncoding("gb2312"));
            sw.WriteLine(
"自动编号,姓名,年龄");
            
foreach(DataRow dr in dt.Rows)
            
{
                sw.WriteLine(dr[
"ID"]+","+dr["vName"]+","+dr["iAge"]);
            }

            sw.Close();
            Response.AddHeader(
"Content-Disposition""attachment; filename=" + Server.UrlEncode(name));
            Response.ContentType 
= "application/ms-excel";
            Response.WriteFile(name);
            Response.End();
        }


        
private void DataGrid1_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
        
{
            
if(e.Item.ItemType==ListItemType.Item||e.Item.ItemType==ListItemType.AlternatingItem||e.Item.ItemType==ListItemType.EditItem)
            
{
                
if(Convert.ToInt16(DataBinder.Eval(e.Item.DataItem,"iAge"))<30)e.Item.BackColor=Color.Pink;
    
            }

        }


        
protected string myfunc(object s)
        
{
            
string _s;
            
if(s.ToString()=="朱晔")
                _s
="<b>"+s.ToString()+"</b>";
            
else
                _s
=s.ToString();
            
return _s;
        }


        
protected string myfunc2(object s1,object s2)
        
{
            
return "newpage.aspx?name="+s1.ToString()+"&age="+s2.ToString();
        }


        
private void Button4_Click(object sender, System.EventArgs e)
        
{
            
if(Request.Form["rad"!= null)
            
{
                rd.Value 
= Request.Form["rad"].ToString();

                
this.Label1.Text = "选择的行号:" + Request.Form["rad"].ToString();
            }


        
        }



        
private void Button5_Click(object sender, System.EventArgs e)
        
{
            
this.Label1.Text="";
            
foreach(DataGridItem di in this.DataGrid1.Items)
            
{
                
if(((CheckBox)di.FindControl("chkExport")).Checked==true)
                
{
                    
this.Label1.Text+=this.DataGrid1.DataKeys[int.Parse(((HtmlInputHidden)di.FindControl("SelectedID")).Value)]+"<br>";
                }

            }

        }


        
private void Button6_Click(object sender, System.EventArgs e)
        
{
            
foreach(DataGridItem di in this.DataGrid1.Items)
            
{
                
                ((CheckBox)di.FindControl(
"chkExport")).Checked=true;
                
            }

        }


        
private void Button7_Click(object sender, System.EventArgs e)
        
{
            
foreach(DataGridItem di in this.DataGrid1.Items)
            
{
                
                ((CheckBox)di.FindControl(
"chkExport")).Checked=false;
                
            }

        
        }

    }



Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=1152029 

导航