使用组合框选择值更新网格视图/ db:ASP.NET C#

时间:2017-01-03 05:06:26

标签: c# asp.net gridview combobox

我需要创建一个包含带有组合框的网格视图的网页。条件是: - 组合框值应插入我的SQL数据库,并在我点击保存按钮时更新数据库/网格视图。[我添加了页面的建议设计图像]任何帮助代码是非常感谢!谢谢!

1 个答案:

答案 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();
}