答案 0 :(得分:2)
GridView标记
下面我有一个从Northwind数据库的Customers表填充的简单GridView ASP.Net GridView控件。它显示2列联系人姓名和城市,可通过ASP.Net DropDownList控件编辑城市。标识符列Customer ID绑定到DataKeyNames属性。
<asp:GridView ID="gvCustomers" DataKeyNames = "CustomerId" runat="server" AutoGenerateColumns = "false" OnRowEditing = "EditCustomer" OnRowDataBound = "RowDataBound" OnRowUpdating = "UpdateCustomer" OnRowCancelingEdit = "CancelEdit">
<Columns>
<asp:BoundField DataField = "ContactName" HeaderText = "Contact Name" />
<asp:TemplateField HeaderText = "City">
<ItemTemplate>
<asp:Label ID="lblCity" runat="server" Text='<%# Eval("City")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblCity" runat="server" Text='<%# Eval("City")%>' Visible = "false"></asp:Label>
<asp:DropDownList ID = "ddlCities" runat = "server">
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Columns>
</asp:GridView>
绑定GridView
下面是使用数据绑定GridView控件的代码。
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindData();
}
}
private void BindData()
{
string query = "SELECT top 10 * FROM Customers";
SqlCommand cmd = new SqlCommand(query);
gvCustomers.DataSource = GetData(cmd);
gvCustomers.DataBind();
}
private DataTable GetData(SqlCommand cmd)
{
string strConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
}
}
编辑GridView行
以下事件处理GridView行编辑和取消编辑事件 C#
protected void EditCustomer(object sender, GridViewEditEventArgs e)
{
gvCustomers.EditIndex = e.NewEditIndex;
BindData();
}
protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
{
gvCustomers.EditIndex = -1;
BindData();
}