在GridView中使用下拉列表框

4
这个问题实际上包含了两个问题。我需要制作一个网格视图,其中一列是下拉选择菜单。
我有以下代码:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="ProjectsODS" OnRowUpdated="GridView1_RowUpdated" DataKeyNames="Id"
    CssClass="mGrid"
    PagerStyle-CssClass="pgr"
    AlternatingRowStyle-CssClass="alt" ShowHeaderWhenEmpty="True" OnRowEditing="GridView1_RowEditing">
    <Columns>
        <asp:BoundField DataField="Name" HeaderText="Project Name" />
        <asp:BoundField DataField="ProjectCode" HeaderText="Code" />
        <asp:TemplateField HeaderText="Access">
            <ItemTemplate>
                <asp:DropDownList runat="server" AutoPostBack="True">
                    <asp:ListItem
                        Enabled="True"
                        Text="No Access"
                        Value="Test" />
                    <asp:ListItem
                        Enabled="True"
                        Text="Read Only"
                        Value="Tes 2" />
                </asp:DropDownList>
            </ItemTemplate>
        </asp:TemplateField>

    </Columns>
</asp:GridView>

最后一列是下拉列表,但目前我正在硬编码其中的项,以查看渲染效果。我需要实际绑定另一个ObjectDataSource中的值。但对于网格中的每一行,它都是相同的数据。它会为每一行命中ODS吗?还是数据只读取一次并由每行使用?
我该如何将ODS链接到DropDownLists?
然后,如何将所选值设置为来自行的值?也就是说,生成gridview的数据源具有名为“AccessTypeId”的字段。我需要使用该值来选择DDL的值。我怎么做?
然后,我设置AutoPostBack为true。一旦用户设置了DDL的新值,我希望它发布该值。但是,当DDL选择的值更改时,网格上发生了什么?
3个回答

1

有一些内置函数可以帮助您完成所有这些操作。

1)关于从数据库加载每行元素,这将不会发生,您只能加载数据一次并将其插入DataTable,然后将每个网格行ddl的数据源设置为该DataTable

如何实现? 有一个名为OnRowDataBound的函数,每个插入GridView中的行都会进入此函数,在此处您可以找到下拉列表并从DataTable设置其listitem。

DataTable dt_Category = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
    using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnStringDb1"].ToString()))
    {
        try
        {
            String cmdText = "SELECT CategoryName FROM Category";
            SqlCommand cmd = new SqlCommand(cmdText, cn);
            //cmd.Parameters.AddWithValue("@IsDeleted", "false");
            cn.Open();
            SqlDataAdapter myAdapter = new SqlDataAdapter(cmd);
            myAdapter.Fill(dt_Category);
            cn.Close();

            GridView1.DataSource = dt_Category;
            GridView1.DataBind();
        }
        catch (Exception ex)
        {
        }
    }
}

protected void RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        //Add you data here
        DropDownList ddl = (DropDownList)e.Row.FindControl("DropDownList1");
        //Bind Data           
    }
}

2)关于获取选定的值,也可以使用内置函数如selectedindexchanged来获取选定的索引,并可使用该索引查找此行的下拉列表,例如row.FindControl("")


1

要将您的ObjectDataSource链接到DropDownList,您可以在标记中完成:

<asp:TemplateField HeaderText="XYZ">
  <ItemTemplate>
    <asp:DropDownList runat="server" ID="MyDD" DataSourceId="MyDataSource" />
  </ItemTemplate> 
</asp:TemplateField>

如果您更喜欢动态绑定下拉列表,可以在RowDataBound甚至是RowCreated事件中进行。以下内容也回答了您的问题:
how do I get the selected value set to be a value from the row? That is, the 
data source that  produces the gridview has a field called "AccessTypeId". 
I need that value to be used to select the value of the DDL. How would I do that

// 这里假设我们检索了 CountryID 的当前行值。然后,我们使用此特定的 CountryID 填充下拉列表中的所有 States 值。

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        string connectionString = WebConfigurationManager.ConnectionStrings[1].ConnectionString;
        SqlConnection con = new SqlConnection(connectionString);
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            con.Open();
            var ddl = (DropDownList)e.Row.FindControl("ddlState");
            int CountryId = Convert.ToInt32(e.Row.Cells[0].Text);
            SqlCommand cmd = new SqlCommand("select * from State where CountryID=" + CountryId, con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);
            con.Close();
            ddl.DataSource = ds;
            ddl.DataTextField = "StateName";
            ddl.DataValueField = "StateID";
            ddl.DataBind();
            ddl.Items.Insert(0, new ListItem("--Select--", "0"));
        }
    }

现在,进入有趣的部分,如何获取DropDownList中选择的值来更新数据库。基本上,您的问题是:
I have set AutoPostBack to true. Once the DDL gets a new value set by the user, 
I want it to post the value.

你应该使用gridView的Update事件来传递下拉列表中选择的新值。你需要先进入编辑模式,然后从下拉列表中选择新值,点击更新按钮并处理GridView的RowUpdating事件。
我使用的方法是定义了自定义的GridView.RowUpdating事件,如下所示。你应该使用此事件来传递你新选择的DropDownList值。
 protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
 {

  DropDownList ddl= (DropDownList )GridView1.Rows[e.RowIndex].FindControl("ddlState");
  string selectedvalue=ddl.selectedvalue;
  //My custom code to change last moment values with that selected from DropDownList 
  e.NewValues.Add("State", selectedvalue);

 }

你的问题是什么:
But, what even on the Grid is called when the DDL selected value is changed

如果您将页面的EnableViewState设置为false,则每个回发都会调用ObjectDataSource Select方法,因此GridView事件也会被调用,例如OnRowDataBound。如果EnableViewStatetrue,则Select方法仅会被调用一次,因此GridView事件也只会被调用一次。 请参考此Stack问题:DataBind and Postback [我已经检查了上述情况下GridView的RowDataBound事件]

0

1- 将数据表作为DropDownList的数据源进行查询

2- 绑定GridView

3- 在RowsDataBound事件中,执行以下操作

protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        //Find the DropDownList in the Row

        DropDownList DropDown = (e.Row.FindControl("DropDown") as DropDownList);
        DropDown.DataSource = TheDatatable;
        DropDown.DisplayMember = "Name";
        DropDown.ValueMember = "ID";
        DropDown.DataBind();

        DropDown.SelectedIndexChanged += new EventHandler(DDL_SelectedIndexChanged);
    }
}

protected void DDL_SelectedIndexChanged(object sender, EventArgs e)
{
    value = ((DropDownList)sender).SelectedValue;
}

添加下拉列表的SelectedIndexChanged事件处理程序。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接