473,472 Members | 2,128 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

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 4196
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Jas | last post by:
I want an ASP page with a dropdown and a simple button. Every time the user chooses an item from the dropdown and clicks on the button i want that value written below in list and allow user to...
2
by: Joachim Bauer | last post by:
I'm using the code below to display a menu that opens when the mouse goes over the main menu item (try it in your browser to understand the behaviour). It uses "position:absolute" and a switch...
6
by: passion_to_be_free | last post by:
This is probably simple, but I can't seem to find it anywhere. I have have some values stored in javascript variables. I have a <select> dropdown list whose options correspond to these values. I...
2
by: Bob Hollness | last post by:
Hi group. I am a newbie to ASP.NET as you will see from some of the questions I may ask! I have a datagrid which I have populated from a database. It works great! I have added a column, via...
2
by: drdave | last post by:
All is working well for my dropdown/datagrid except I cannot figure out how to set my ddl selected index when the value is blank/null. ie before edit mode the lblVariation text value is blank.....
1
by: Anup | last post by:
Hi Group, I have a datagrid with dropdown in my application. I want to fill the data in dropdown by an ArrayList for that I am using "e.Item.FindControl("DropdownId")" but this function is...
6
by: yasodhai | last post by:
Hi, I used a dropdown control which is binded to a datagrid control. I passed the values to the dropdownlist from the database using a function as follows in the aspx itself. <asp:DropDownList...
1
by: RichardR | last post by:
I have a webpage which has a table that contains a column with several drop down boxes (<SELECT>). The contents of the drop down boxes are dynamically populated so I have no idea what the actually...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.