Reputation: 23
How can I set the default value for the dropdown generated by the GridView in editing mode?
This is how I try:
- DropDown items have been added statically (no database)
- I've set a EditItemTemplate and created a Dropdown
I'm wondering how can I set the default value based on the current value of the editing row? Which events should I try and how?
Following your solution I have encountered this error. Any ideas?
Object reference not set to an instance of an object!!!
.aspx related controls elements
<asp:TemplateField ShowHeader="False">
<EditItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True"
CommandName="Update" Font-Names="B Zar" Font-Size="14pt" ForeColor="#FFFFCC"
Text="ثبت"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False"
CommandName="Cancel" ForeColor="#FFFFCC" Text="لغو"></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False"
CommandName="Edit" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" Text="ویرایش"></asp:LinkButton>
</ItemTemplate>
<ItemStyle Font-Names="B Zar" Font-Size="14pt" ForeColor="#0066FF" />
</asp:TemplateField>
DropDownList HTML Code:
<asp:DropDownList ID="ddDegree" runat="server" Height="32px" Width="132px"
Font-Names="B Zar" Font-Size="14pt" >
<asp:ListItem value="0">انتخاب کنید</asp:ListItem>
<asp:ListItem>یک </asp:ListItem>
<asp:ListItem>دو</asp:ListItem>
<asp:ListItem>سه</asp:ListItem>
<asp:ListItem>جهار </asp:ListItem>
<asp:ListItem>پنج </asp:ListItem>
<asp:ListItem>شش</asp:ListItem>
<asp:ListItem>هفت</asp:ListItem>
<asp:ListItem>هشت</asp:ListItem>
Upvotes: 0
Views: 1603
Reputation: 2592
You could use OnRowCommand
event on your gridview like this:
<asp:GridView ID="GridView1" OnRowCommand="GridView1_RowCommand" .. <Columns> <asp:TemplateField> <ItemTemplate> <asp:DropDownList ID="DropDownList1" runat="server"> </asp:DropDownList> ....
lets say you have edit button on your gridview row, then you need to set a command name property on your control like this one:
<asp:Button ID="Button1" runat="server" Text="Button" CommandName="edit" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />
And in your event method you just need to set your dropdownlist like this:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
int index = 0;
GridViewRow gridRow;
switch (e.CommandName)
{
case "edit":
index = Convert.ToInt32(e.CommandArgument);
gridRow = GridView1.Rows[index];
//get your dropdownlist from the selected gridview row
DropDownList ddl1 = gridRow.FindControl("DropDownList1") as DropDownList;
//make the dropdownlist selected based on your given value
ddl1.Items.FindByValue("set your value here").Selected = true;
break;
}
}
Upvotes: 1