ASP.NET2.0中用Gridview控件操作数据
【IT168 技术文档】
首先,我们打算在让用户进行选择,当用户需要新增一记录时,便点击新增按钮,之后在Gridview的最后一行里,显示一个空白行,让用户按字段进行输入,当用户决定不输入新空白记录时,可以按"cancel"按钮返回,该空白行消失。要实现这样的效果,我们可以充分利用Gridview的footer的模版功能进行自定义,因为有3列,所以,在每一列的footer模版中,定义如下:
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>
("ContactTitleDropDownList") as DropDownList;
SqlDataSource1.InsertParameters["CustomerID"].DefaultValue = customerID.Text;
SqlDataSource1.InsertParameters["CompanyName"].DefaultValue = companyName.Text;
SqlDataSource1.InsertParameters["ContactTitle"].DefaultValue=ContactTitle.SelectedValue;
SqlDataSource1.Insert();
}
</script>
[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>