0
votes

I am using ASP.NET and C# to design a gridview. The gridview has two bound fields (NAME and CODE) and one template dropdownlist(PAY) field.

The Gridview is populated using a Database DB1 which returns the NAME, CODE and PAY. I am able to fetch these values as expected and populate the NAME and CODE fields of the gridview.

                 <asp:BoundField DataField="NAME" HeaderText="NAME" 
                SortExpression="NAME" />
            <asp:BoundField DataField="CODE" HeaderText="CODE" SortExpression="CODE" />
            <asp:TemplateField HeaderText="PAY" SortExpression="PAY"> 
                <ItemTemplate> 
                    <asp:DropDownList ID="DropDownList1" runat="server" DataTextField="CODE" DataValueField="CODE" 
                    OnSelectedIndexChanged="DropDownList_SelectedIndexChanged" AutoPostBack="True" AppendDataBoundItems="true">
                        <asp:ListItem Text="Choose New Value"></asp:ListItem>   
                    </asp:DropDownList> 
                </ItemTemplate> 
            </asp:TemplateField> 

The list of possible values for the template Dropdownlist is bound using data fetched from a different DataSource DB2. I am able to fetch these values and populate the dropdownlist successfully.

My requirement is that the PAY field returned by the gridview's database DB1 query should be set as the default value of the dropdown initially.

Kindly help me in this regard.

Thanks

1
cant you do something like this DropDownLIst1.selectedText="Something" - zxc

1 Answers

0
votes

You can use GridView1_RowDataBound event to handle this

    void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DropDownList ddl = (DropDownList)e.Row.FindControl("DropDownList1");

            if (ddl != null)
            {

                ListItem li = ddl.Items.FindByText(DataBinder.Eval(e.Row.DataItem, "CODE").ToString());

                if (li != null)
                    li.Selected = true;

            }


        }
    }