利用DataGrid編輯、修改、刪除記錄

來源:互聯網
上載者:User
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] (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>

本文評論(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();
}




相關文章

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。