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

80酷酷网    80kuku.com

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



<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='

<%# 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>

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



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


分享到
  • 微信分享
  • 新浪微博
  • QQ好友
  • QQ空间
点击: