ASP.NET 2.0中用Gridview控件操作數據

  在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="U
PDATE [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);
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章