Edit, modify, and delete records using the DataGrid

Source: Internet
Author: User
Tags dsn eval integer modify mysql tostring trim
DataGrid 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] (MB) COLLATE chinese_prc_ci_as NULL,
[LastName] [Char] (MB) 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-I SQL
String sql = "";
String strcnn = "Data source=.;i Nitial 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=.;i Nitial 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" >

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> A-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>

This article reviews (Comments): To protect your email from harassment, the individual symbols in the address are converted to Full-width characters!
Reviewer: Ling e-mail: yblin@163. COM Review Date: June 12, 2004 03:51:07
I have no way to achieve the deletion function! I don't know why!!! can help solve!!



Dim rcount,pcount,currentpage As Integer
Sub Page_Load (sender As Object, E as EventArgs) ' first load
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) ' Change page
MyList. CurrentPageIndex = E.newpageindex
DataBind ()
End Sub
Sub Page_onclick (sender as object,e as CommandEventArgs) ' response button
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 = "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 () ' Determines whether the button is available or not
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 ' format output character
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 ' intercept character
if (Str_biaoti. LENGTH&GT;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 ();
}




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.