利用DataGrid编辑、修改、删除记录

类别:.NET开发 点击:0 评论:0 推荐:
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[People]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [dbo].[People] GO CREATE TABLE [dbo].[People] ( [pkID] [int] IDENTITY (1, 1) NOT NULL , [FirstName] [char] (100) COLLATE Chinese_PRC_CI_AS NULL , [LastName] [char] (100) COLLATE Chinese_PRC_CI_AS NULL ) ON [PRIMARY] GO

EditDataGridCS.aspx

<%@ Page Language="c#" debug="true"%> <%@ Import Namespace="System.Data"%> <%@ Import Namespace="System.Data.SqlClient" %> <script runat="server"> //make first sql String sql = ""; String strCnn = "Data Source=.;Initial Catalog=aa;User Id=sa;Password=;"; //create a datasource function public ICollection CreateDataSource () { SqlConnection conn = new SqlConnection(strCnn); SqlDataAdapter db_sqladaptor = new SqlDataAdapter(sql,conn); DataSet ds = new DataSet(); db_sqladaptor.Fill(ds,"MyDataResult"); DataView myView = ds.Tables["MyDataResult"].DefaultView; return myView; } //do page load public void Page_Load(Object sender, EventArgs e) { strCnn = "Data Source=.;Initial Catalog=aa;User Id=sa;Password=;"; if (!IsPostBack) { sql = "Select * FROM People"; People.DataSource = CreateDataSource(); People.DataBind(); } } public void Page_Grid(Object sender, DataGridPageChangedEventArgs e) { sql = "Select * FROM People"; // Set CurrentPageIndex to the page the user clicked. People.CurrentPageIndex = e.NewPageIndex; // Rebind the data. People.DataSource = CreateDataSource(); People.DataBind(); } public void People_Edit(Object sender, DataGridCommandEventArgs e) { sql = "Select * FROM People"; People.EditItemIndex = e.Item.ItemIndex; People.DataSource = CreateDataSource(); People.DataBind(); } public void People_Cancel(Object sender, DataGridCommandEventArgs e) { sql = "Select * FROM People"; People.EditItemIndex = -1; People.DataSource = CreateDataSource(); People.DataBind(); } public void People_Update(Object sender, DataGridCommandEventArgs e) { string FirstName = ((TextBox)e.Item.Cells[1].Controls[1]).Text; string LastName = ((TextBox)e.Item.Cells[2].Controls[1]).Text; SqlConnection connUpdate = new SqlConnection(strCnn); connUpdate.Open(); String sql_edit = "UPDATE People " + "SET FirstName = '" + FirstName.Replace("'","''")+ "'," + "LastName = '" + LastName.Replace("'","''")+ "'" + " WHERE pkID = " + e.Item.Cells[0].Text; SqlCommand sqlCommandUpdate = new SqlCommand(sql_edit,connUpdate); sqlCommandUpdate.ExecuteNonQuery(); connUpdate.Close(); sql = "Select * FROM People"; People.EditItemIndex = -1; People.DataSource = CreateDataSource(); People.DataBind(); } public void People_Delete(Object sender, DataGridCommandEventArgs e) { SqlConnection connDel = new SqlConnection(strCnn); connDel.Open(); String sql_Del = "DELETE FROM People " + " WHERE pkID = " + e.Item.Cells[0].Text; SqlCommand sqlCommandDel = new SqlCommand(sql_Del,connDel); sqlCommandDel.ExecuteNonQuery(); connDel.Close(); sql = "Select * FROM People"; People.EditItemIndex = -1; People.DataSource = CreateDataSource(); People.DataBind(); } </script> <font face="arial" size="3"> <b>Edit People</b> </font> <br> <form runat="server"> <asp:DataGrid id="People" runat="server" BorderColor="green" Width="640" PageSize="5" AllowPaging="true" OnPageIndexChanged="Page_Grid" BorderWidth="1" CellPadding="3" AutoGenerateColumns="false" ShowHeader="true" Visible="true" OnEditCommand="People_Edit" OnCancelCommand="People_Cancel" OnUpdateCommand="People_Update" OnDeleteCommand="People_Delete"> <HeaderStyle BorderColor="White" BackColor="black" ForeColor="White" Font-Bold="True" Font-Name="Arial" Font-Size="9" HorizontalAlign="Center"/> <ItemStyle BorderColor="" BackColor="#FFFFF0" ForeColor="Black" Font-Name="Arial" Font-Size="8" Font-Bold="False" HorizontalAlign="Center"/> <EditItemStyle BorderColor="" BackColor="#FFFFF0" ForeColor="Black" Font-Name="Arial" Font-Size="7" Font-Bold="False" HorizontalAlign="Center"/> <PagerStyle Mode="NumericPages" Font-Size="8"/> <Columns> <asp:BoundColumn HeaderText="ID" ReadOnly="true" DataField="pkID"/> <asp:TemplateColumn> <HeaderTemplate> <b> First Name </b> </HeaderTemplate> <ItemTemplate> <asp:Label Text='<%# DataBinder.Eval(Container.DataItem, "FirstName").ToString().Trim() %>' runat="server"/> </ItemTemplate> <EditItemTemplate> <asp:TextBox id="FirstName" Text=' <%# DataBinder.Eval(Container.DataItem, "FirstName").ToString().Trim() %>' runat="server" Width="100%"/> </EditItemTemplate> </asp:TemplateColumn> <asp:TemplateColumn> <HeaderTemplate> <b> Last Name </b> </HeaderTemplate> <ItemTemplate> <asp:Label Width="200" Text='<%# DataBinder.Eval(Container.DataItem, "LastName").ToString().Trim() %>' runat="server"/> </ItemTemplate> <EditItemTemplate> <asp:TextBox id="LastName" Text='<br> <%# DataBinder.Eval(Container.DataItem, "LastName").ToString().Trim() %>' runat="server" Width="100%"/> </EditItemTemplate> </asp:TemplateColumn> <asp:EditCommandColumn ButtonType="LinkButton" CancelText="Cancel" EditText="Edit" UpdateText="Update" /> <asp:ButtonColumn Text= "Delete" CommandName="Delete"></asp:ButtonColumn> </Columns> </asp:DataGrid> </form>
    新闻管理系统
      
       
        AllowPaging="True"       
    PagerStyle-Visible="false" 
PageSize="10"  
OnPageIndexChanged="change_page"  
    runat="server" 
    Width="550"
    GridLines="None"
    ShowFooter="false" 
    CellPadding="2"
    CellSpacing="1"
    Font-Name="宋体"
    Font-Size="8pt" 
    EnableViewState="false"
    AutoGenerateColumns="false" 
DataKeyField="id" 
    OnDeleteCommand="Mylist_Delete">
 
 
                          HeaderText=""    
                DataNavigateUrlField="id"    
                DataNavigateUrlFormatString="newsedit.aspx?id={0}"    
                DataTextField="标题"    
                 >

     
     



    



  
      
      
     
共有条记录      
当前为/

" target="manage frame">添加新闻

  
  本文评论(Comments):为了保护您的电子邮件不被骚扰,地址中的个别符号转换成了全角字符!
  评论人:凌风雁 电子邮件:yblin@163.com 评论日期:2004年06月12日 03:51:07
  我这个没有办法实现删除功能!不知道为什么!!!可不可以帮助解决一下!!
<%@ import namespace="system.data" %>
<%@ import namespace="system.data.oledb" %>

dim rcount,pcount,CurrentPage as integer
sub page_load(sender as object, e as eventargs)  '首次载入
if not page.IsPostBack then
   dim mana as string
   mana = request.QueryString("mname")
   if mana ="" then
      response.Redirect("/manage/admin.aspx")
      exit sub
   end if
   session("managename") = mana
   dim cn As OleDbConnection
   Dim cmd As OleDbDataadapter
   dim ds as dataset
   Dim sql As String = "select * from news order by id desc"
   dim dsn As String = application("dsn")
   cn = new oledbconnection(dsn)
   cmd = new oledbdataadapter
   cmd.tablemappings.add("Table","news")
   cmd.selectcommand = new oledbcommand(sql,cn)
   ds = new dataset("news")
   cmd.fill(ds,"news")
   RCount = ds.tables("news").defaultview.Count
   CurrentPage = 1
   if (RCount mod MyList.PageSize) = 0 then
      Pcount = Rcount/MyList.PageSize
      lblRecordCount.Text = RCount.ToString()  
      lblPageCount.Text = PCount.ToString()  
      lblCurrentPage.Text= "1"
   else 
      Pcount =cint( rcount/MyList.PageSize + 0.5)
  lblRecordCount.Text = RCount.ToString()  
      lblPageCount.Text = PCount.ToString()  
      lblCurrentPage.Text = "1"
   end if
   listsize()
   mylist.datasource = ds.tables("news").defaultview
   mylist.databind()
end if
end sub
sub change_page(sender As Object, e As DataGridPageChangedEventArgs) '换页
    mylist.CurrentPageIndex = e.NewPageIndex
   databind()
end sub
sub Page_OnClick(sender as object,e as commandeventargs) '响应按钮 
   CurrentPage = cint(lblCurrentPage.Text)
   PCount = cint(lblPageCount.Text)
   dim cmd1 as string
   cmd1 = e.CommandName
if cmd1 = "Next" then  
         if (CurrentPage < (PCount)) then 
 CurrentPage = currentpage + 1 
 end if
end if
if cmd1 = "Prev" then  
         if (CurrentPage > 0) then
 CurrentPage = currentpage - 1
 end if
end if
if cmd1 = "First" then  
      CurrentPage = 1
end if  
if cmd1 = "Last" then  
      CurrentPage = (PCount)
end if 
lblCurrentPage.Text = CurrentPage 
Listsize()
MyList.CurrentPageIndex = currentpage - 1
   databind()
end sub
sub Mylist_Delete(sender as object, e as DataGridCommandEventArgs)
dim mycn As OleDbConnection
    dim mycmd as OleDbCommand
Dim mysql As String = "delete from news where id = @id"
    dim mydsn As String = application("dsn")
mycn = New OleDbConnection(mydsn)
    mycmd = New OleDbCommand(mysql,mycn)
mycmd.Parameters.Add(New oledbParameter("@id",oledbtype.integer,4))
mycmd.Parameters("@id").Value =mylist.DataKeys(cint(e.Item.ItemIndex).tostring())
mycmd.Connection.Open()
    mycmd.ExecuteNonQuery()
mycmd.Connection.Close()
databind()
end sub    
function databind()
   dim cn As OleDbConnection
   Dim cmd As OleDbDataadapter
   dim ds as dataset
   Dim sql As String = "select * from news order by id desc"
   dim dsn As String = application("dsn")
   cn = new oledbconnection(dsn)
   cmd = new oledbdataadapter
   cmd.tablemappings.add("Table","news")
   cmd.selectcommand = new oledbcommand(sql,cn)
   ds = new dataset("news")
   cmd.fill(ds,"news")
   mylist.datasource = ds.tables("news").defaultview
   mylist.databind()
end function
function listsize()  '判断按钮可用与否
   lbnNextPage.Enabled = true  
   lbnPrevPage.Enabled = true 
   lbnLastPage.Enabled = true  
   lbnFirstPage.Enabled = true  
   if CurrentPage = PCount then    
      lbnNextPage.Enabled = false  
      lbnLastPage.Enabled = false
   end if
   if CurrentPage = 1 then 
   lbnPrevPage.Enabled = false 
   lbnFirstPage.Enabled = false  
   end if
   if currentpage = 1 and pcount = 1 then
   lbnNextPage.Enabled = false  
   lbnPrevPage.Enabled = false 
   lbnLastPage.Enabled = false 
   lbnFirstPage.Enabled = false
   end if 
end function
function formatstring(str as string) as string  '格式化输出字符
  str=str.replace(" ","  ")
  str=str.replace("<","<")
  str=str.replace(">",">")
  str=str.replace(vbcrlf,"
")
  formatstring = str
end function
function getchar(str_biaoti as string) as string  '截取字符
  if (str_biaoti.Length>20)
   return str_biaoti.Substring(0,20)+"……" 
  else 
   return str_biaoti
  end if
end function







 
    function newwin(url) 
     { 
    var popup; 
    url=url; 
    popup=window.open(url,null,"top=5,left=5,width=600,resizable=no,height=500,menubar=no,toolbar=no,scrollbars=yes,status=no"); 
    popup.focus(); 
     } 



  
  




  评论人:lqidiot 电子邮件:lq9904@tom.com 评论日期:2004年04月12日 03:37:10   有没有用VB.NET语言写的,
我写了一个,但是不能实现"更新"这一功能
程序如下,能不能帮我改正一下
多谢了

 Dim conn As New SqlClient.SqlConnection("server=(local); database=lq; user id=sa; password=506")
        conn.Open()
        Dim Cmd As SqlClient.SqlCommand
        Dim SQL As String
        SQL = "Update zhuce Set [学号]=@学号, [姓名]=@姓名, [性别]=@性别, [专业]=@专业  Where [学号]=@Key"
        Cmd = New SqlClient.SqlCommand(SQL, conn)
        Cmd.Parameters.Add(New SqlClient.SqlParameter("@学号", SqlDbType.Int))
        Cmd.Parameters.Add(New SqlClient.SqlParameter("@姓名", SqlDbType.Char, 10))
        Cmd.Parameters.Add(New SqlClient.SqlParameter("@性别", SqlDbType.Char, 2))
        Cmd.Parameters.Add(New SqlClient.SqlParameter("@专业", SqlDbType.Char, 25))
        Cmd.Parameters.Add(New SqlClient.SqlParameter("@Key", SqlDbType.Int))
        Dim TB(4) As TextBox
        TB(1) = e.Item.Cells(2).Controls(0) ' 学号 TextBox
        TB(2) = e.Item.Cells(3).Controls(0) ' 姓名 TextBox                                                                    
        TB(3) = e.Item.Cells(4).Controls(0) ' 性别 TextBox
        TB(4) = e.Item.Cells(5).Controls(0) ' 专业 TextBox
        Label1.Text = Val(TB(1).Text) & TB(2).Text & TB(3).Text & TB(4).Text
        Cmd.Parameters("@Key").Value = mygrid.DataKeys(e.Item.ItemIndex)
        Cmd.Parameters("@学号").Value = Val(TB(1).Text)
        Cmd.Parameters("@姓名").Value = TB(2).Text
        Cmd.Parameters("@性别").Value = TB(3).Text
        Cmd.Parameters("@专业").Value = TB(4).Text
        Cmd.ExecuteNonQuery()
        Label2.Text = Cmd.Parameters("@学号").Value & Cmd.Parameters("@姓名").Value & Cmd.Parameters("@性别").Value & Cmd.Parameters("@专业").Value
        conn.Close()
        mygrid.EditItemIndex = -1
        open_bind()
  评论人:aloner007 电子邮件:aloner_007@163.com 评论日期:2004年03月26日 08:47:47   String strCnn = "Data Source=.;Initial Catalog=aa;User Id=sa;Password=;";  //这句语句是什么意思?
db_sqladaptor.Fill(ds,"MyDataResult");中的MyDataResult参数是什么意思!
  评论人:http://dotnet.aspx.cc 电子邮件:http://dotnet.aspx.cc 评论日期:2004年02月05日 12:36:23   http://dotnet.aspx.cc

本文地址:http://com.8s8s.com/it/it44137.htm