473,695 Members | 3,090 Online
Bytes | Software Development & Data Engineering Community
+ 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:TemplateCo lumn HeaderText="Dro pDown">
<ItemTemplate >
<asp:Label runat="server" Text='<%# DataBinder.Eval
(Container, "DataItem.Choic eId") %>' ID="lblChoiceId ">
</asp:Label>
</ItemTemplate>
<EditItemTempla te>
<asp:DropDownLi st ID="ddnChoiceId " runat="server">
<asp:ListItem Value="Inactive ">Inactive</asp:ListItem>
<asp:ListItem Value="Active"> Active</asp:ListItem>
</asp:DropDownLis t>
</EditItemTemplat e>
</asp:TemplateCol umn>

Codebehind:
protected void OnEdit(object source,
System.Web.UI.W ebControls.Data GridCommandEven tArgs eA)
{
myGrid.EditItem Index = eA.Item.DataSet Index;
ListItemType ddLister = eA.Item.ItemTyp e;
if ( ddLister == ListItemType.Ed itItem )
{
DataRowView ddView = eA.Item.DataIte m;
DropDownList ddTemp = eA.Item.FindCon trol
( "ddnChoiceI d" );
// 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 4215
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:TemplateCo lumn HeaderText="Dro pDown">
<ItemTemplate >
<asp:Label runat="server" Text='<%# DataBinder.Eval
(Container, "DataItem.Choic eId") %>' ID="lblChoiceId ">
</asp:Label>
</ItemTemplate>
<EditItemTempla te>
<asp:DropDownLi st ID="ddnChoiceId " runat="server">
<asp:ListItem Value="Inactive ">Inactive</asp:ListItem>
<asp:ListItem Value="Active"> Active</asp:ListItem>
</asp:DropDownLis t>
</EditItemTemplat e>
</asp:TemplateCol umn>

Codebehind:
protected void OnEdit(object source,
System.Web.UI.W ebControls.Data GridCommandEven tArgs eA)
{
myGrid.EditItem Index = eA.Item.DataSet Index;
ListItemType ddLister = eA.Item.ItemTyp e;
if ( ddLister == ListItemType.Ed itItem )
{
DataRowView ddView = eA.Item.DataIte m;
DropDownList ddTemp = eA.Item.FindCon trol
( "ddnChoiceI d" );
// 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("ChoiceI D")) li.Selected=tru e;

--

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

protected void OnEdit(object source,
System.Web.UI.W ebControls.Data GridCommandEven tArgs
dgCmdEvArgs)
{
grdUserAppRoles .EditItemIndex =
dgCmdEvArgs.Ite m.DataSetIndex;
ListItemType ddLister = dgCmdEvArgs.Ite m.ItemType;
DataRowView ddView = (DataRowView)
dgCmdEvArgs.Ite m.DataItem;
DropDownList ddTemp = (DropDownList)
dgCmdEvArgs.Ite m.FindControl( "ddnChoiceI d" );
foreach (ListItem li in ddTemp.Items)
{
if ( li.Value == ddTemp.Selected Value )
{
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.W ebControls.Data GridCommandEven tArgs
dgCmdEvArgs)
{
grdUserAppRoles .EditItemIndex = dgCmdEvArgs.Ite m.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.W ebControls.Data GridItemEventAr gs)
ListItemType ddLister = dgCmdEvArgs.Ite m.ItemType;
if(ddLister==Li stItemType.Edit Item) {
DataRowView ddView = (DataRowView)
dgCmdEvArgs.Ite m.DataItem;
DropDownList ddTemp = (DropDownList)
dgCmdEvArgs.Ite m.FindControl( "ddnChoiceI d" );
foreach (ListItem li in ddTemp.Items)
{
if ( li.Value == ddTemp.Selected Value )
{
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 EditItemTemplat e 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.DataIte m;
DropDownList ddTemp = eA.Item.FindCon trol
( "ddnChoiceI d" );

the DropDownList hasn't been created at the DataGrid's EditCommand event,
so we are unable to retrieve it using the "FindContro l". 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:TemplateCo lumn>
<ItemTemplate >
<%# DataBinder.Eval (Container.Data Item,"gender") %>
</ItemTemplate>
<EditItemTempla te>
<asp:DropDownLi st ID="lstGender" OnLoad="lstGend er_Load" Runat="server">
<asp:ListItem Value="male">Ma le</asp:ListItem>
<asp:ListItem Value="female"> Female</asp:ListItem>
</asp:DropDownLis t>
</EditItemTemplat e>
</asp:TemplateCol umn>

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

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

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

private void gridTest_EditCo mmand(object source,
System.Web.UI.W ebControls.Data GridCommandEven tArgs e)
{
gridTest.EditIt emIndex = e.Item.ItemInde x;
gridTest.DataSo urce = Get_Data();//Get_Data() returns a DataTable for
testing
gridTest.DataBi nd();
}

#notice that the "gridTest_EditC ommand" is called before the
"lstGender_Load ", that also indicate that the DropDownList hasn't been
created when the DataGrid_EditCo mmand 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.as px-----------

<%@ Page language="c#" Codebehind="Dat aGridEdit.aspx. cs"
AutoEventWireup ="false" Inherits="MyWeb App.DataGridEdi t" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>DataGrid Edit</title>
<meta content="Micros oft Visual Studio .NET 7.1" name="GENERATOR ">
<meta content="C#" name="CODE_LANG UAGE">
<meta content="JavaSc ript" name="vs_defaul tClientScript">
<meta content="http://schemas.microso ft.com/intellisense/ie5"
name="vs_target Schema">
</HEAD>
<body>
<form id="Form1" method="post" runat="server">
<table width="500" align="center">
<tr>
<td><asp:datagr id id="gridTest" runat="server"
AutoGenerateCol umns="False">
<Columns>
<asp:TemplateCo lumn>
<ItemTemplate >
<%# DataBinder.Eval (Container.Data Item,"id") %>
</ItemTemplate>
</asp:TemplateCol umn>
<asp:TemplateCo lumn>
<ItemTemplate >
<%# DataBinder.Eval (Container.Data Item,"name") %>
</ItemTemplate>
<EditItemTempla te>
<input type="text" value='<%#
DataBinder.Eval (Container.Data Item,"name") %>'/>
</EditItemTemplat e>
</asp:TemplateCol umn>
<asp:TemplateCo lumn>
<ItemTemplate >
<%# DataBinder.Eval (Container.Data Item,"email") %>
</ItemTemplate>
<EditItemTempla te>
<input type="text" value='<%#
DataBinder.Eval (Container.Data Item,"email") %>'/>
</EditItemTemplat e>
</asp:TemplateCol umn>
<asp:TemplateCo lumn>
<ItemTemplate >
<%# DataBinder.Eval (Container.Data Item,"gender") %>
</ItemTemplate>
<EditItemTempla te>
<asp:DropDownLi st ID="lstGender" OnLoad="lstGend er_Load"
Runat="server">
<asp:ListItem Value="male">Ma le</asp:ListItem>
<asp:ListItem Value="female"> Female</asp:ListItem>
</asp:DropDownLis t>
</EditItemTemplat e>
</asp:TemplateCol umn>
<asp:EditComman dColumn ButtonType="Lin kButton" UpdateText="Upd ate"
CancelText="Can cel" EditText="Edit" ></asp:EditCommand Column>
</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.as px.cs-----------------------------
using System;
using System.Collecti ons;
using System.Componen tModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.Sess ionState;
using System.Web.UI;
using System.Web.UI.W ebControls;
using System.Web.UI.H tmlControls;

namespace MyWebApp
{
/// <summary>
/// Summary description for DataGridEdit.
/// </summary>
public class DataGridEdit : System.Web.UI.P age
{
protected System.Web.UI.W ebControls.Text Box txtTest;
protected System.Web.UI.W ebControls.Data Grid gridTest;

private void Page_Load(objec t sender, System.EventArg s e)
{
// Put user code to initialize the page here
if(!IsPostBack)
{
gridTest.DataSo urce = Get_Data();
gridTest.DataBi nd();
}

}

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(EventArg s e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeCompo nent();
base.OnInit(e);
}

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeCompo nent()
{
this.gridTest.E ditCommand += new
System.Web.UI.W ebControls.Data GridCommandEven tHandler(this.g ridTest_EditCom m
and);
this.Load += new System.EventHan dler(this.Page_ Load);

}
#endregion


protected void lstGender_Load( object source, System.EventArg s e)
{
DropDownList lstGender = (DropDownList)s ource;
DataTable tb = (DataTable)grid Test.DataSource ;
DataRow row = tb.Rows[gridTest.EditIt emIndex];

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

}

private void gridTest_EditCo mmand(object source,
System.Web.UI.W ebControls.Data GridCommandEven tArgs e)
{
gridTest.EditIt emIndex = e.Item.ItemInde x;
gridTest.DataSo urce = Get_Data();
gridTest.DataBi nd();
}

}
}


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(CheckDBNu ll(Me.Restauran tsDataset.Table s(0).Rows(TODO: INDEX
SHOULD GO HERE)("ServingT ypeCode")), String).Trim
Case "B"
servingType.Ite ms(0).Selected = True
Case "L"
servingType.Ite ms(1).Selected = True
Case "D"
servingType.Ite ms(2).Selected = True
Case "BL"
servingType.Ite ms(0).Selected = True
servingType.Ite ms(1).Selected = True
Case "BD"
servingType.Ite ms(0).Selected = True
servingType.Ite ms(2).Selected = True
Case "LD"
servingType.Ite ms(1).Selected = True
servingType.Ite ms(2).Selected = True
Case "BLD"
servingType.Ite ms(0).Selected = True
servingType.Ite ms(1).Selected = True
servingType.Ite ms(2).Selected = True
End Select
End Sub
Nov 18 '05 #6
here is the list item

<EditItemTempla te>


<asp:CheckBoxLi st Runat="server"
Id="EditServing Type" OnLoad="EditSer vingType_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:CheckBoxLis t>
</EditItemTemplat e>

-----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(CheckDBN ull(Me.Restaura ntsDataset.Tabl es(0).Rows (TODO: INDEXSHOULD GO HERE)("ServingT ypeCode")), String).Trim
Case "B"
servingType.Ite ms(0).Selected = True
Case "L"
servingType.Ite ms(1).Selected = True
Case "D"
servingType.Ite ms(2).Selected = True
Case "BL"
servingType.Ite ms(0).Selected = True
servingType.Ite ms(1).Selected = True
Case "BD"
servingType.Ite ms(0).Selected = True
servingType.Ite ms(2).Selected = True
Case "LD"
servingType.Ite ms(1).Selected = True
servingType.Ite ms(2).Selected = True
Case "BLD"
servingType.Ite ms(0).Selected = True
servingType.Ite ms(1).Selected = True
servingType.Ite ms(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
9619
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 select more. Also how can these choices be saved somehow so tha when the user goes to the next page the choices he made can be written to the database. For example The choices in the dropdown may be
2
6435
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 between "display='none'" and "display=''". However the problem is that - in Internet Explorer 6 the dropdown (<select>...) always hides the menu
6
3467
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 want to be able to select an item on the dropdown list based on the value of the javascript variable. Let's say this is my list and my variable: <select id='popup'>
2
2432
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 the Columns dialog box from the properties of the datagrid, on the left that contains a select button. So now, when you press the button the whole row is highlighted. Now, what I want to do is have the user highlight as many rows as they wish...
2
1631
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.. This routine sets the value strVariation Sub dgMinimumWage_EditRow(sender as Object, e As DataGridCommandEventArgs)
1
2870
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 returning NULL THUS I m getting exception "Object Refrence not set to an Instance to Object", Here is the code I wrote (ASP.NET 1.1)...
6
5849
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 ID="FldType_add" Runat="server" DataSource='< %#GetFieldType()%>' DataValueField="Type" DataTextField="Type" /> Oce the page is loaded all the values are added to the dropdown list. But when I thought of getting the selected value from the...
1
24322
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 width will be necessary. How do I tell the dropdown (<SELECT>) and/or column (<TD>) to automatically size itself to the greater of widest item in the dropdown, and then get the smaller dropdowns to fill the width of the column? If I specify in...
0
9122
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9001
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8860
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8832
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6498
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 presenter, Adolph Dupr who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5841
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4348
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3018
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2281
muto222
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.