Select Item in DropDown in DataGrid?

L

localhost

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

Jos

localhost said:
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;
 
L

localhost

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
 
J

Jos

localhost said:
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...
 
M

MSFT

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.DataGridCommandEventHandler(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.)
 
P

Paul

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
 
G

Guest

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

Steven Cheng[MSFT]

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-us/dnaspp/html/creatingcustomcolumns.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.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top