GridView中的DropDownList

时间:2013-08-10 11:40:52

标签: c# asp.net

这个问题实际上是两个问题。我需要生成一个gridview,其中一列是下拉选项。

我有以下代码:

<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一次,并被每一行使用?

如何将ODS链接到DropDownLists?

然后,如何将所选值设置为行中的值?也就是说,生成gridview的数据源有一个名为“AccessTypeId”的字段。我需要使用该值来选择DDL的值。我该怎么做?

然后,我将AutoPostBack设置为true。一旦DDL获得用户设置的新值,我希望它发布该值。但是,当DDL选择值改变时,甚至在Grid上调用什么?

3 个答案:

答案 0 :(得分:1)

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

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

如何吗 有一个名为OnRowDataBound的函数,在gridview中插入的每一行都将转到此函数,您可以在此处找到下拉列表并从数据表中设置其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 :(得分: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的所有状态值填充下拉列表。

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"));
        }
    }

现在,有趣的是how to get the selected value in DropDownlist to update the database。基本上你的问题:

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事件来传递从下拉列表中选择的新值。您需要先处于编辑模式,然后从DropDownList中选择新值,单击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事件]

答案 2 :(得分: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事件处理程序