473,788 Members | 2,707 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 4224
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
9621
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
6440
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
3469
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
2440
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
1637
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
2879
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
5857
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
24391
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
9498
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10113
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
9969
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...
0
8995
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7519
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
6750
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
5538
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3677
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2896
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.