小弟新寫的一篇文章,原文發表在http://dev.yesky.com/msdn/283/2018783.shtml上,因為沒圖,比較方便摘錄如下:
在ASP.NET 2.0中,加入了許多新的功能和控制項,相比asp.net 1.0/1.1,在各方面都有了很大的提高。其中,在資料控制項方面,增加了不少控制項,其中的Gridview控制項功能十分強大。在本文中,將探討Gridview控制項中的一些功能特性和用法,如果各位讀者對Gridview控制項不大瞭解,可以通過《使用ASP.NET 2.0中的Gridview控制項》一文,來對Gridview控制項有個初步的認識。
1、使用Gridview插入新記錄
在Gridview控制項中,可以實現插入新記錄的操作(見《使用ASP.NET 2.0中的Gridview控制項》)一文,但如果想實現在Gridview中,實現在Gridview控制項的最後一行,提供一個空白行給使用者輸入要輸入的記錄,那無疑是很方便的。下面將介紹其實現方法。
首先,我們打算在讓使用者進行選擇,當使用者需要新增一記錄時,便點擊新增按鈕,之後在Gridview的最後一行裡,顯示一個空白行,讓使用者按欄位進行輸入,如所示:
當使用者決定不輸入新空白記錄時,可以按"cancel"按鈕返回,該空白行消失。要實現這樣的效果,我們可以充分利用Gridview的footer的模版功能進行自訂,因為有3列,所以,在每一列的footer模版中,定義如下:
<asp:Gridview ID="Gridview1" Runat="server" DataSourceID="SqlDataSource1" DataKeyNames="CustomerID" AutoGenerateColumns="False" ShowFooter="True"> <Columns> <asp:TemplateField> <ItemTemplate> <asp:Label ID="CustomerIDLabel" Runat="Server"><%# Eval("CustomerID") %></asp:Label> </ItemTemplate> <FooterTemplate> <asp:TextBox ID="CustomerIDTextBox" Runat="server"></asp:TextBox> </FooterTemplate> </asp:TemplateField> <asp:TemplateField> <ItemTemplate> <asp:Label ID="CompanyNameLabel" Runat="Server"><%# Eval("CompanyName") %></asp:Label> </ItemTemplate> <FooterTemplate> <asp:TextBox ID="CompanyNameTextBox" Runat="server"></asp:TextBox> </FooterTemplate> </asp:TemplateField> <asp:TemplateField> <FooterTemplate> <asp:DropDownList ID="ContactTitleDropDownList" Runat="server" DataSourceID="SqlDataSource2" DataTextField="ContactTitle" DataValueField="ContactTitle"> </asp:DropDownList> <asp:SqlDataSource ID="SqlDataSource2" Runat="server" SelectCommand="SELECT DISTINCT [ContactTitle] FROM [Customers]" ConnectionString="server=localhost;uid=sa;password=xxx;database=northwind"> </asp:SqlDataSource> <asp:Button ID="Button1" Runat="server" Text="Add" OnClick="Button1_Click" /> <asp:Button ID="CancelButton1" Runat="server" Text="Cancel" OnClick="CancelButton1_Click" /> </FooterTemplate> <ItemTemplate> <asp:DropDownList ID="ContactTitleDropDown" SelectedValue=’<%# Bind("ContactTitle") %>’ Runat="Server" DataSourceID="SqlDataSource3" DataTextField="ContactTitle" DataValueField="ContactTitle" ></asp:DropDownList> <asp:SqlDataSource ID="SqlDataSource3" Runat="server" SelectCommand="SELECT DISTINCT [ContactTitle] FROM [Customers]" ConnectionString="server=localhost;uid=sa;password=xxxx;database=northwind" EnableCaching="True"> </asp:SqlDataSource> </ItemTemplate> </asp:TemplateField> </Columns> </asp:Gridview> |
以上為Gridview的代碼,可以看到,在第一,二列的<foottemplate>列中,分別提供了customerid和companyname兩個文字框以供使用者輸入,在第三列的<footertemplate>列中,以dropdownlistbox的形式來顯示contracttitle.。其中,請注意第三列的footertemplate中的add和cancel兩個按鈕的,它們的事件代碼如下
<script runat="server"> void CancelButton1_Click(object sender, EventArgs e) { Gridview1.ShowFooter = false; } void AddButton1_Click(object sender, EventArgs e) { Gridview1.ShowFooter = true; } //點add按鈕時,將新增的記錄更新到資料庫中去 void Button1_Click(object sender, EventArgs e) { TextBox customerID = Gridview1.FooterRow.FindControl("CustomerIDTextBox") as TextBox; TextBox companyName = Gridview1.FooterRow.FindControl("CompanyNameTextBox") as TextBox; DropDownList ContactTitle = Gridview1.FooterRow.FindControl("ContactTitleDropDownList") as DropDownList; SqlDataSource1.InsertParameters["CustomerID"].DefaultValue = customerID.Text; SqlDataSource1.InsertParameters["CompanyName"].DefaultValue = companyName.Text; SqlDataSource1.InsertParameters["ContactTitle"].DefaultValue=ContactTitle.SelectedValue; SqlDataSource1.Insert(); } </script> |
其中的cancel按鈕的事件,用來取消顯示Gridview的footer模版,因此設定showfooter屬性為false,而addbutton1按鈕,是當使用者決定新增記錄時點選的,此時將設定showfooter屬性為true,以顯示各列的foottemplate,從而達到顯示新的一個空白行的目的。
而在更新代碼button1_click事件中,將首先使用Gridview1.footerrow.findcontrol的方法,將使用者新增的各欄位的值提取出來,然後分別賦值給sqldatasource的insertparameters集合(注意要一一對應),最後使用sqldatasource的insert方法,就可以成功向資料庫增加一條新記錄了。
另外,為了在表單載入時,顯示資料庫northwind中customers表的資料,需要設定sqldatsource1的屬性,如下代碼:
<asp:SqlDataSource ID="SqlDataSource1" Runat="server" InsertCommand="INSERT INTO [Customers] ([CustomerID], [CompanyName], [ContactTitle]) VALUES (@CustomerID, @CompanyName, @ContactTitle)" SelectCommand="SELECT top 5 [CustomerID], [CompanyName], [ContactTitle] FROM [Customers]" ConnectionString="server=localhost;uid=sa;password=XXXXX;database=northwind"> <InsertParameters> <asp:Parameter Type="String" Name="CustomerID"></asp:Parameter> <asp:Parameter Type="String" Name="CompanyName"></asp:Parameter> <asp:Parameter Type="String" Name="ContactTitle"></asp:Parameter> </InsertParameters> </asp:SqlDataSource> |
其中,必須設定insertcommand和selectcommand屬性,設定資料提取和插入的語句,並且要設定好insertparameters集合中,各欄位的類型和名稱即可。
2、一次性更新所有的Gridview記錄
我們經常會遇到這樣的情況,在Gridview中列出的所有記錄中,有時要同時修改多條記錄,並且將其儲存到資料庫中去。那麼在Gridview中應該如何?呢?在Gridview中,有兩種實現的方法,下面分別進行介紹:
先來看下第一種方法,本方法是使用sqldatasource來更新所有記錄,但這個方法比較慢,因為每更新一條記錄都要建立資料連線並執行updatecommand,會影響效能。其主要代碼如下:
<script runat="server"> void Button1_Click(object sender, EventArgs e) { for (int i = 0; i < Gridview1.Rows.Count; i++) { GridviewRow row = Gridview1.Rows[i]; SqlDataSource1.UpdateParameters[0].DefaultValue = ((TextBox)row.Cells[0].FindControl("TextBox2")).Text; SqlDataSource1.UpdateParameters[1].DefaultValue = ((TextBox)row.Cells[1].FindControl("TextBox3")).Text; SqlDataSource1.UpdateParameters[2].DefaultValue = Gridview1.DataKeys[i].Value.ToString(); SqlDataSource1.Update(); } } </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Gridview ID="Gridview1" Runat="server" DataSourceID="SqlDataSource1" DataKeyNames="CustomerID" AutoGenerateColumns="False"> <Columns> <asp:TemplateField SortExpression="CustomerID" HeaderText="CustomerID"> <ItemTemplate> <asp:TextBox Runat="server" Text=’<%# Bind("CustomerID") %>’ ID="TextBox1"></asp:TextBox> </ItemTemplate> </asp:TemplateField> <asp:TemplateField SortExpression="CompanyName" HeaderText="CompanyName"> <ItemTemplate> <asp:TextBox Runat="server" Text=’<%# Bind("CompanyName") %>’ ID="TextBox2"></asp:TextBox> </ItemTemplate> </asp:TemplateField> <asp:TemplateField SortExpression="ContactName" HeaderText="ContactTitle"> <ItemTemplate> <asp:TextBox Runat="server" Text=’<%# Bind("ContactTitle") %>’ ID="TextBox3"></asp:TextBox> </ItemTemplate> </asp:TemplateField> </Columns> </asp:Gridview> <asp:SqlDataSource ID="SqlDataSource1" Runat="server" SelectCommand="SELECT [CustomerID], [CompanyName], [ContactName], [ContactTitle] FROM [Customers]" UpdateCommand="UPDATE [Customers] SET [CompanyName] = @CompanyName, [ContactTitle] = @ContactTitle WHERE [CustomerID] = @CustomerID" ConnectionString="server=localhost;uid=sa;password=xxxx;database=northwind"> <UpdateParameters> <asp:Parameter Type="String" Name="CompanyName"></asp:Parameter> <asp:Parameter Type="String" Name="ContactTitle"></asp:Parameter> <asp:Parameter Type="String" Name="CustomerID"></asp:Parameter> </UpdateParameters> </asp:SqlDataSource> <asp:Button ID="Button1" Runat="server" Text="Button" OnClick="Button1_Click" /> </div> </form> </body> </html> |
在上面的代碼中,我們必須首先指定updateparameters參數集合,也就是指出要更新的是哪些欄位,它們的類型是什麼。之後並指出sqldatasource的updatecommand語句。而在更新按鈕button1的CLICK事件中,將以遍曆的形式,使用for迴圈,對Gridview中的每一行進行檢查,將每個更新了的文字框的內容放到sqldatasouce的updateparameters參數中去,最後調用sqldatasource的update方法,完成更新。
方法2使用的是首先遍曆Gridview中的每一行,並且使用SQL語句,將要更新的內容串連起來,然後最後才使用command.ExecuteNonQuery()進行更新,效率高了,主要代碼如下:
protected void Page_Load(object sender, EventArgs e) {if (!Page.IsPostBack) { SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["AppConnectionString1"].ConnectionString); SqlCommand command = new SqlCommand("SELECT [CustomerID], [CompanyName], [ContactName], [ContactTitle] FROM [Customers]", con); con.Open(); Gridview1.DataSource = command.ExecuteReader(); Gridview1.DataBind(); con.Close(); } } protected void Button1_Click(object sender, EventArgs e) { StringBuilder query = new StringBuilder(); for (int i = 0; i < Gridview1.Rows.Count; i++) { GridviewRow row = Gridview1.Rows[i]; string value1 = ((TextBox)row.Cells[0].FindControl("TextBox2")).Text.Replace("’", "’’"); string value2 = ((TextBox)row.Cells[1].FindControl("TextBox3")).Text.Replace("’", "’’"); string value3 = Gridview1.DataKeys[i].Value.ToString(); query.Append("UPDATE [Customers] SET [CompanyName] = ’").Append(value1).Append("’ , [ContactTitle] = ’") .Append(value2).Append("’ WHERE [CustomerID] = ’").Append(value3).Append("’;\n"); } SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["AppConnectionString1"].ConnectionString); SqlCommand command = new SqlCommand(query.ToString(), con); con.Open(); command.ExecuteNonQuery(); con.Close(); } } |
其中要特別注意一點的是,在vs.net 2005 beta 2開始,如果你在web.config中使用了資料庫連接字串的配置,那麼應該按如下的方法去寫:
<connectionStrings> <add name="NorthwindConnectionString" connectionString="Data Source=LIAO;Initial Catalog=Northwind;User ID=sa;Password=xxxx" providerName="System.Data.SqlClient"/> </connectionStrings> |
然後在程式中如下進行讀取:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["AppConnectionString1"].ConnectionString); |