469,282 Members | 2,000 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,282 developers. It's quick & easy.

Select Item in DropDown in DataGrid?

A DataGrid with shows a label in one of the columns when
in view mode. When in edit mode, I want to show a
dropdown, and have the default selection set to what the
textbox used to be. Right now the first item in the
dropdown is always displayed.

Template Code:
<asp:TemplateColumn HeaderText="DropDown">
<ItemTemplate>
<asp:Label runat="server" Text='<%# DataBinder.Eval
(Container, "DataItem.ChoiceId") %>' ID="lblChoiceId">
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddnChoiceId" runat="server">
<asp:ListItem Value="Inactive">Inactive</asp:ListItem>
<asp:ListItem Value="Active">Active</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateColumn>

Codebehind:
protected void OnEdit(object source,
System.Web.UI.WebControls.DataGridCommandEventArgs eA)
{
myGrid.EditItemIndex = eA.Item.DataSetIndex;
ListItemType ddLister = eA.Item.ItemType;
if ( ddLister == ListItemType.EditItem )
{
DataRowView ddView = eA.Item.DataItem;
DropDownList ddTemp = eA.Item.FindControl
( "ddnChoiceId" );
// I found the control, now what do I do ?
//
}

Actually, I am not sure if this will work at all.... Any
suggesstions appreciated. Thanks.
Nov 18 '05 #1
7 3974
Jos
localhost wrote:
A DataGrid with shows a label in one of the columns when
in view mode. When in edit mode, I want to show a
dropdown, and have the default selection set to what the
textbox used to be. Right now the first item in the
dropdown is always displayed.

Template Code:
<asp:TemplateColumn HeaderText="DropDown">
<ItemTemplate>
<asp:Label runat="server" Text='<%# DataBinder.Eval
(Container, "DataItem.ChoiceId") %>' ID="lblChoiceId">
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddnChoiceId" runat="server">
<asp:ListItem Value="Inactive">Inactive</asp:ListItem>
<asp:ListItem Value="Active">Active</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateColumn>

Codebehind:
protected void OnEdit(object source,
System.Web.UI.WebControls.DataGridCommandEventArgs eA)
{
myGrid.EditItemIndex = eA.Item.DataSetIndex;
ListItemType ddLister = eA.Item.ItemType;
if ( ddLister == ListItemType.EditItem )
{
DataRowView ddView = eA.Item.DataItem;
DropDownList ddTemp = eA.Item.FindControl
( "ddnChoiceId" );
// I found the control, now what do I do ?
//
}

Actually, I am not sure if this will work at all.... Any
suggesstions appreciated. Thanks.


I'm assuming from your code that the ChoiceID field contains either
Active or Inactive.

Something like this might work:

foreach (ListItem li in ddTemp.Items)
if (li.Value == ddView("ChoiceID")) li.Selected=true;

--

Jos
Nov 18 '05 #2
Still no go. My codebehind looks like this:

protected void OnEdit(object source,
System.Web.UI.WebControls.DataGridCommandEventArgs
dgCmdEvArgs)
{
grdUserAppRoles.EditItemIndex =
dgCmdEvArgs.Item.DataSetIndex;
ListItemType ddLister = dgCmdEvArgs.Item.ItemType;
DataRowView ddView = (DataRowView)
dgCmdEvArgs.Item.DataItem;
DropDownList ddTemp = (DropDownList)
dgCmdEvArgs.Item.FindControl( "ddnChoiceId" );
foreach (ListItem li in ddTemp.Items)
{
if ( li.Value == ddTemp.SelectedValue )
{
li.Selected = true;
}
}
.....

But for starters, ddLister is casting to null.

Help?

But
Nov 18 '05 #3
Jos
localhost wrote:
Still no go. My codebehind looks like this:

protected void OnEdit(object source,
System.Web.UI.WebControls.DataGridCommandEventArgs
dgCmdEvArgs)
{
grdUserAppRoles.EditItemIndex = dgCmdEvArgs.Item.DataSetIndex;
Stop here with OnEdit, but not before you perform DataBinding:

grdUserAppRoles.DataBind();
}

Then, do the rest in OnItemDataBound:

protected void OnItemDataBound(object source,
System.Web.UI.WebControls.DataGridItemEventArgs)
ListItemType ddLister = dgCmdEvArgs.Item.ItemType;
if(ddLister==ListItemType.EditItem) {
DataRowView ddView = (DataRowView)
dgCmdEvArgs.Item.DataItem;
DropDownList ddTemp = (DropDownList)
dgCmdEvArgs.Item.FindControl( "ddnChoiceId" );
foreach (ListItem li in ddTemp.Items)
{
if ( li.Value == ddTemp.SelectedValue )
{
li.Selected = true;
}
}
....


Hope this helps...

--

Jos
Nov 18 '05 #4
Hi localhost,
Welcome to Microsoft Newsgroup Service. Based on your problem description,
you have a DataGrid with a Template column, in which, the ItemTemplate is a
Lable and the EditItemTemplate is a DropDownList, and you want to set the
DropDownList's selectedIndex according to the value when show in the
Label(not in edit mode), is my understanding correct?

I've tested the code you provided, I found that there are something
incorrect when run it. Such as :
DataRowView ddView = eA.Item.DataItem;
DropDownList ddTemp = eA.Item.FindControl
( "ddnChoiceId" );

the DropDownList hasn't been created at the DataGrid's EditCommand event,
so we are unable to retrieve it using the "FindControl". Don't worry,
though we can't retrieve the DropDownList in the DataGrid's EditCommand
event, there is another way we initialize its value. You can specify a
"OnLoad" event handler for the DropDownList, for example:
<asp:TemplateColumn>
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem,"gender") %>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="lstGender" OnLoad="lstGender_Load" Runat="server">
<asp:ListItem Value="male">Male</asp:ListItem>
<asp:ListItem Value="female">Female</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateColumn>

Then, implement this handler function("lstGender_Load") in the Page Class:
protected void lstGender_Load(object source, System.EventArgs e)
{
DropDownList lstGender = (DropDownList)source;
//get the datasource of the DataGrid(you should change it to other
//if you don't use DataTAble as the datasource)
DataTable tb = (DataTable)gridTest.DataSource;
DataRow row = tb.Rows[gridTest.EditItemIndex];

if(row["gender"].Equals("male"))
{
lstGender.SelectedIndex = 0;
}
else
{
lstGender.SelectedIndex = 1;
}

}
Then, in the DataGrid's EditCommand event, you just need to set its
EditItemIndex and rebind the data:

private void gridTest_EditCommand(object source,
System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
gridTest.EditItemIndex = e.Item.ItemIndex;
gridTest.DataSource = Get_Data();//Get_Data() returns a DataTable for
testing
gridTest.DataBind();
}

#notice that the "gridTest_EditCommand" is called before the
"lstGender_Load", that also indicate that the DropDownList hasn't been
created when the DataGrid_EditCommand event is fired.

Please try the preceding suggestion and let me know whether they help.

Below is my test page and its page class's source

----------------DataGridEdit.aspx-----------

<%@ Page language="c#" Codebehind="DataGridEdit.aspx.cs"
AutoEventWireup="false" Inherits="MyWebApp.DataGridEdit" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>DataGridEdit</title>
<meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
<meta content="C#" name="CODE_LANGUAGE">
<meta content="JavaScript" name="vs_defaultClientScript">
<meta content="http://schemas.microsoft.com/intellisense/ie5"
name="vs_targetSchema">
</HEAD>
<body>
<form id="Form1" method="post" runat="server">
<table width="500" align="center">
<tr>
<td><asp:datagrid id="gridTest" runat="server"
AutoGenerateColumns="False">
<Columns>
<asp:TemplateColumn>
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem,"id") %>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn>
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem,"name") %>
</ItemTemplate>
<EditItemTemplate>
<input type="text" value='<%#
DataBinder.Eval(Container.DataItem,"name") %>'/>
</EditItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn>
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem,"email") %>
</ItemTemplate>
<EditItemTemplate>
<input type="text" value='<%#
DataBinder.Eval(Container.DataItem,"email") %>'/>
</EditItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn>
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem,"gender") %>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="lstGender" OnLoad="lstGender_Load"
Runat="server">
<asp:ListItem Value="male">Male</asp:ListItem>
<asp:ListItem Value="female">Female</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateColumn>
<asp:EditCommandColumn ButtonType="LinkButton" UpdateText="Update"
CancelText="Cancel" EditText="Edit"></asp:EditCommandColumn>
</Columns>
</asp:datagrid></td>
</tr>
<tr>
<td><FONT face="">
<asp:TextBox id="txtTest" runat="server"></asp:TextBox></FONT>
</td>
</tr>
</table>
</form>
</body>
</HTML>

---------------DataGridEdit.aspx.cs-----------------------------
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace MyWebApp
{
/// <summary>
/// Summary description for DataGridEdit.
/// </summary>
public class DataGridEdit : System.Web.UI.Page
{
protected System.Web.UI.WebControls.TextBox txtTest;
protected System.Web.UI.WebControls.DataGrid gridTest;

private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
if(!IsPostBack)
{
gridTest.DataSource = Get_Data();
gridTest.DataBind();
}

}

protected DataTable Get_Data()
{
DataTable tb = new DataTable();
tb.Columns.Add("id");
tb.Columns.Add("name");
tb.Columns.Add("email");
tb.Columns.Add("gender");

for(int i=0;i<20;i++)
{
DataRow row = tb.NewRow();
row["id"] = i+1;
row["name"] = "Name" + i.ToString();
row["email"] = "Email" + i.ToString();
if(i%2 == 0)
{
row["gender"] = "male";
}
else
{
row["gender"] = "female";
}

tb.Rows.Add(row);
}

return tb;

}

#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.gridTest.EditCommand += new
System.Web.UI.WebControls.DataGridCommandEventHand ler(this.gridTest_EditComm
and);
this.Load += new System.EventHandler(this.Page_Load);

}
#endregion


protected void lstGender_Load(object source, System.EventArgs e)
{
DropDownList lstGender = (DropDownList)source;
DataTable tb = (DataTable)gridTest.DataSource;
DataRow row = tb.Rows[gridTest.EditItemIndex];

if(row["gender"].Equals("male"))
{
lstGender.SelectedIndex = 0;
}
else
{
lstGender.SelectedIndex = 1;
}

}

private void gridTest_EditCommand(object source,
System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
gridTest.EditItemIndex = e.Item.ItemIndex;
gridTest.DataSource = Get_Data();
gridTest.DataBind();
}

}
}


Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)

Nov 18 '05 #5
Hello Steven,
I saw your code for the onLoad event for a dropdownlist in a
datagrid, and that was exactly what I needed for the problem I had
with a checkboxlist.
However, I have one problem that I've been trying to figure out.

I have multiple rows in the grid. How do I pass the index of that row
to the onload event handler. Here's my code. The checkboxlist have 3
list items with values B, L and D (Breakfast, Lunch, Dinner).

Notice the TODO: in the row index.

Public Sub EditServingType_Load(ByVal source As Object, ByVal e As
EventArgs)
Dim servingType As CheckBoxList = CType(source, CheckBoxList)

Select Case
CType(CheckDBNull(Me.RestaurantsDataset.Tables(0). Rows(TODO: INDEX
SHOULD GO HERE)("ServingTypeCode")), String).Trim
Case "B"
servingType.Items(0).Selected = True
Case "L"
servingType.Items(1).Selected = True
Case "D"
servingType.Items(2).Selected = True
Case "BL"
servingType.Items(0).Selected = True
servingType.Items(1).Selected = True
Case "BD"
servingType.Items(0).Selected = True
servingType.Items(2).Selected = True
Case "LD"
servingType.Items(1).Selected = True
servingType.Items(2).Selected = True
Case "BLD"
servingType.Items(0).Selected = True
servingType.Items(1).Selected = True
servingType.Items(2).Selected = True
End Select
End Sub
Nov 18 '05 #6
here is the list item

<EditItemTemplate>


<asp:CheckBoxList Runat="server"
Id="EditServingType" OnLoad="EditServingType_Load"
RepeatDirection="Horizontal">
<asp:ListItem Value="B">B</asp:ListItem>
<asp:ListItem Value="L">L</asp:ListItem>
<asp:ListItem Value="D">D</asp:ListItem>
</asp:CheckBoxList>
</EditItemTemplate>

-----Original Message-----
Hello Steven,
I saw your code for the onLoad event for a dropdownlist in adatagrid, and that was exactly what I needed for the problem I hadwith a checkboxlist.
However, I have one problem that I've been trying to figure out.
I have multiple rows in the grid. How do I pass the index of that rowto the onload event handler. Here's my code. The checkboxlist have 3list items with values B, L and D (Breakfast, Lunch, Dinner).
Notice the TODO: in the row index.

Public Sub EditServingType_Load(ByVal source As Object, ByVal e AsEventArgs)
Dim servingType As CheckBoxList = CType(source, CheckBoxList)
Select Case
CType(CheckDBNull(Me.RestaurantsDataset.Tables(0) .Rows (TODO: INDEXSHOULD GO HERE)("ServingTypeCode")), String).Trim
Case "B"
servingType.Items(0).Selected = True
Case "L"
servingType.Items(1).Selected = True
Case "D"
servingType.Items(2).Selected = True
Case "BL"
servingType.Items(0).Selected = True
servingType.Items(1).Selected = True
Case "BD"
servingType.Items(0).Selected = True
servingType.Items(2).Selected = True
Case "LD"
servingType.Items(1).Selected = True
servingType.Items(2).Selected = True
Case "BLD"
servingType.Items(0).Selected = True
servingType.Items(1).Selected = True
servingType.Items(2).Selected = True
End Select
End Sub
.

Nov 18 '05 #7
Hi meritex,
Thanks for your followup. As for the problem you mentioned---get the
current editindex of the grid in the list's onload event. I think you can
add a global variable of the page scope. such as
class my page: Page
{
protected int m_editindex;
.....
}

Then set the value in the Grid's EditCommand event and use it in the
dropdownlist or checkbox's onload event. Do you think it ok?

Also, I've found another tech article in MSDN which provides another good
solution for the databind column in DataGrid.

http://msdn.microsoft.com/library/en...stomcolumns.as
p?frame=true

I believe it will be helpful to you.

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)
Nov 18 '05 #8

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

6 posts views Thread by passion_to_be_free | last post: by
2 posts views Thread by Bob Hollness | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by suresh191 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.