Craig
Craig

Reputation: 18734

DropDownList in GridView

This question is actually two questions. I need to produce a gridview, with one column being a drop down selection.

I have the following code:

<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>

The last column is indeed a drop down. But, at the moment, I am hard coding items in it, to see how it will render. I need to actually bind values from another ObjectDataSource. But for each row in the grid, it's the same data. Will it hit the ODS for each row, or is the data read into the ODS once, and used by each row?

How do I link the ODS to the DropDownLists?

Then, 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?

And then, I have set AutoPostBack to true. Once the DDL gets a new value set by the user, I want it to post the value. But, what even on the Grid is called when the DDL selected value is changed?

Upvotes: 4

Views: 5368

Answers (3)

R.C
R.C

Reputation: 10565

To link your objectDataSource to DropDownList, you can do that in Markup:

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

If you prefer to bind dropdownlists dynamically, you can do so in RowDataBound or even in RowCreated event as below. This also answers your question:

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

// Here suppose we retrieve the current rows value for CountryID. Then we populate the dropdownlist with all values of States for this particular 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"));
        }
    }

Now, comes the interesting part, how to get the selected value in DropDownlist to update the database . Basically your Question:

I have set AutoPostBack to true. Once the DDL gets a new value set by the user, 
I want it to post the value.

You should use the Update event of gridView to pass your new value selected from dropdownlist. You need to be first in edit mode, then, select the new value from DropDownList, click the Update button and handle the GridView's RowUpdating event.

One i'm using is that I defined my custom GridView.RowUpdating Event as below. You should use this event to pass your newly selected DropDownList value.

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

 }

And your Question:

But, what even on the Grid is called when the DDL selected value is changed

In case you have set your page's EnableViewState to false, the ObjectDataSource Select method will be called for each postback & hence the GridView events will be called too like the OnRowDataBound. If EnableViewState is true, the Select method will be called only once and hence the GridView events. Refer this Stack Question: DataBind and Postback

[ I had checked the GridView's RowDataBound event for the above cases ]

Upvotes: 1

Ahmed Alaa El-Din
Ahmed Alaa El-Din

Reputation: 1833

There are some built-in functions will help you to do all of this.

1)About loading elements from database each row,this will not happen you can load data only once and insert it into DataTable and set Datasource of each grid row ddl to that DataTable

How? there is a function called OnRowDataBound ,every row being inserted inside the gridview will go to this function here you can find the drop down list and set its listitem from the datatable.

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)About getting the selected value,also built-in function like selectedindexchanged will get you the selected index and can use it to find the dropdown of this row like row.FindControl("")

Upvotes: 1

Michael B.
Michael B.

Reputation: 2809

1- Query datatable as the DropDownList source

2- Bind the GridView

3- On RowsDataBound, do something like this

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

Note adding SelectedIndexChanged event handler of the dropdownlist

Upvotes: 0

Related Questions