473,840 Members | 1,425 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Edit DataGrid Dropdown cell

ASP.NET 2003

In the DataGrid how do I select current cell value in the dropdown box when
I click on the edit link, currently when I click on the edit link in the
DataGrid the dropdown box appears in the cell, but allways the first item in
the dropdown box is shown not the current cell value?

How do I make the current value in the cell automaticaly be selected in the
dropdown box.
// Code Behind

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;
using System.Data.Sql Client;

namespace DataGridDemo
{
/// <summary>
/// Summary description for WebForm4.
/// </summary>
public class Dropdown : System.Web.UI.P age
{
protected System.Web.UI.W ebControls.Data Grid DataGrid1;
protected System.Data.Sql Client.SqlConne ction sqlConnection1;

private void Page_Load(objec t sender, System.EventArg s e)
{
BindData();
}

private void BindData()
{
// Select from the authors table of the pubs database
SqlCommand sqlCmd = new SqlCommand("SEL ECT * FROM Employees",
sqlConnection1) ;
sqlCmd.CommandT ype = CommandType.Tex t;

sqlConnection1. Open();
// Set the data source for this datagrid to the datareader
// returned from the ExecuteReader method
DataGrid1.DataS ource = sqlCmd.ExecuteR eader();

// Bind the datagrid to the datasource
DataGrid1.DataB ind();
sqlConnection1. Close();
}

public ICollection LoadNames()
{
// A new connection must be created because the one
// used for binding the DataGrid is still in use.
SqlConnection sqlNewConnectio n = new SqlConnection() ;
sqlNewConnectio n.ConnectionStr ing = sqlConnection1. ConnectionStrin g;

SqlDataAdapter da = new SqlDataAdapter( "SELECT FirstName FROM Employees",
sqlNewConnectio n);
DataSet ds = new DataSet();
da.Fill(ds);

return ds.Tables[0].DefaultView;
}

#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.sqlConnect ion1 = new System.Data.Sql Client.SqlConne ction();
//
// sqlConnection1
//
this.sqlConnect ion1.Connection String = "workstatio n id=DEVCON4SVR;p acket
size=4096;user id=sa;data source=DEVCON4S VR;pers" +
"ist security info=False;init ial catalog=Northwi nd";
this.sqlConnect ion1.InfoMessag e += new
System.Data.Sql Client.SqlInfoM essageEventHand ler(this.sqlCon nection1_InfoMe ssage);
this.DataGrid1. CancelCommand += new
System.Web.UI.W ebControls.Data GridCommandEven tHandler(this.O nCancel);
this.DataGrid1. EditCommand += new
System.Web.UI.W ebControls.Data GridCommandEven tHandler(this.O nEdit);
this.DataGrid1. UpdateCommand += new
System.Web.UI.W ebControls.Data GridCommandEven tHandler(this.O nUpdate);
this.DataGrid1. SelectedIndexCh anged += new
System.EventHan dler(this.DataG rid1_SelectedIn dexChanged);
this.Load += new System.EventHan dler(this.Page_ Load);

}
#endregion

private void OnEdit(object source,
System.Web.UI.W ebControls.Data GridCommandEven tArgs e)
{
DataGrid1.EditI temIndex = e.Item.DataSetI ndex;
BindData();
}

private void OnUpdate(object source,
System.Web.UI.W ebControls.Data GridCommandEven tArgs e)
{
// Find the drop down list
DropDownList DropList = (DropDownList)e .Item.FindContr ol("dlNames");
string strTest = DropList.Select edItem.Text;

// Process updated data here

DataGrid1.EditI temIndex = -1;
BindData();
}

private void OnCancel(object source,
System.Web.UI.W ebControls.Data GridCommandEven tArgs e)
{
DataGrid1.EditI temIndex = -1;
BindData();
}

private void sqlConnection1_ InfoMessage(obj ect sender,
System.Data.Sql Client.SqlInfoM essageEventArgs e)
{

}

private void DataGrid1_Selec tedIndexChanged (object sender,
System.EventArg s e)
{

}
}
}

// ASPX page

<%@ Page language="c#" Codebehind="Dro pdown.aspx.cs" AutoEventWireup ="false"
Inherits="DataG ridDemo.Dropdow n" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>WebForm3 </title>
<meta content="Micros oft Visual Studio 7.0" 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 MS_POSITIONING= "GridLayout ">
<form id="WebForm3" method="post" runat="server">
<asp:datagrid id="DataGrid1" style="Z-INDEX: 101; LEFT: 11px; POSITION:
absolute; TOP: 45px" runat="server"
AutoGenerateCol umns="False">
<Columns>
<asp:EditComman dColumn ButtonType="Lin kButton" UpdateText="Upd ate"
CancelText="Can cel" EditText="Edit" ></asp:EditCommand Column>
<asp:TemplateCo lumn HeaderText="Fir st Name">
<ItemTemplate >
<asp:Label runat="server" Text='<%# DataBinder.Eval (Container,
"DataItem.First Name") %>'>
</asp:Label>
</ItemTemplate>
<EditItemTempla te>
<asp:dropdownli st ID="dlNames" DataSource='<%# LoadNames() %>'
DataTextField=" FirstName" runat="server">
</asp:dropdownlis t>
</EditItemTemplat e>
</asp:TemplateCol umn>
<asp:TemplateCo lumn HeaderText="Las t Name">
<ItemTemplate >
<asp:Label runat="server" Text='<%# DataBinder.Eval (Container,
"DataItem.LastN ame") %>'>
</asp:Label>
</ItemTemplate>
<EditItemTempla te>
<asp:TextBox runat="server" Text='<%# DataBinder.Eval (Container,
"DataItem.LastN ame") %>'>
</asp:TextBox>
</EditItemTemplat e>
</asp:TemplateCol umn>
<asp:TemplateCo lumn HeaderText="Cit y">
<ItemTemplate >
<asp:Label runat="server" Text='<%# DataBinder.Eval (Container,
"DataItem.city" ) %>'>
</asp:Label>
</ItemTemplate>
<EditItemTempla te>
<asp:TextBox runat="server" Text='<%# DataBinder.Eval (Container,
"DataItem.city" ) %>'>
</asp:TextBox>
</EditItemTemplat e>
</asp:TemplateCol umn>
</Columns>
</asp:datagrid>&n bsp;</form>
</body>
</HTML>
May 25 '06 #1
2 2862
Hi Peter,

Thank you for post!

You will have to manually set the DropDownList's SelectedIndex property
according to the current record's FirstName field value, you can do this in
DataGrid's ItemDataBound event.

Here's the sample code:

--------------
private void DataGrid1_ItemD ataBound(object sender,
System.Web.UI.W ebControls.Data GridItemEventAr gs e)
{
if (e.Item.ItemTyp e == ListItemType.Ed itItem )
{
string currentName = DataBinder.Eval (e.Item.DataIte m, "FirstName" )
as string ;
DropDownList ddl = e.Item.FindCont rol("dlNames") as DropDownList;
for (int i = 0; i < ddl.Items.Count ; i++)
{
ListItem item = ddl.Items[i];
if (item.Text == currentName)
{
ddl.SelectedInd ex = i;
break;
}
}
}
}
--------

Hope this helps. If there's anything unclear, please feel free to post here.

Regards,
Walter Wang
Microsoft Online Community Support

=============== =============== =============== =====
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
=============== =============== =============== =====

This posting is provided "AS IS" with no warranties, and confers no rights.

May 25 '06 #2
Thank You very much, this is what I needed !
"Walter Wang [MSFT]" <wa****@online. microsoft.com> wrote in message
news:WH******** ******@TK2MSFTN GXA01.phx.gbl.. .
Hi Peter,

Thank you for post!

You will have to manually set the DropDownList's SelectedIndex property
according to the current record's FirstName field value, you can do this
in
DataGrid's ItemDataBound event.

Here's the sample code:

--------------
private void DataGrid1_ItemD ataBound(object sender,
System.Web.UI.W ebControls.Data GridItemEventAr gs e)
{
if (e.Item.ItemTyp e == ListItemType.Ed itItem )
{
string currentName = DataBinder.Eval (e.Item.DataIte m, "FirstName" )
as string ;
DropDownList ddl = e.Item.FindCont rol("dlNames") as DropDownList;
for (int i = 0; i < ddl.Items.Count ; i++)
{
ListItem item = ddl.Items[i];
if (item.Text == currentName)
{
ddl.SelectedInd ex = i;
break;
}
}
}
}
--------

Hope this helps. If there's anything unclear, please feel free to post
here.

Regards,
Walter Wang
Microsoft Online Community Support

=============== =============== =============== =====
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
=============== =============== =============== =====

This posting is provided "AS IS" with no warranties, and confers no
rights.

May 25 '06 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
6607
by: Tamir Khason | last post by:
How to prevent the selected cell from being editable (visual) at DataGrid? Once click on cell (even readonly) there are cursor inside it and select text appears. How to prevent it Thankx
0
873
by: Alex | last post by:
I have a column that shows a string based on a join with an other table that has an index to string mapping. The main table is referencing the "helper" table. While in the edit mode of the datagrid I would like to make it look like a dropdown box selection. How can I do that?
2
3762
by: Dave | last post by:
Hi, I'm building a maintenance form for a table and some of the fields are textboxes (i.e name) and some should be dropdowns (i.e country of origin) When a user clicks 'Edit' in the <asp:EditCommandColumn> I want either a textbox or dropdown to appear when I check what is being edited. I thought I could create the dropdown on the fly and add it to the datagrid as below but It's not appearing. I imagined I could populate the dropdown
3
4380
by: Tim::.. | last post by:
Can someone please tell me how I go about preselecting an item in a drop drown list when I click the Edit Command in a datagrid? I have tried the following but it doesn't work for me! I would be really grateful for any assistance! Thanks
3
1516
by: Schultz | last post by:
is there an easy to follow, source code in one document, article that explains how to create an edit all DataGrid control? and, I have a DataGrid setup where the client enters information for each row by clicking Edit-Update for each row. Each row has several columns, is there anyway to move the Edit function to edit each column individually for each row in the DataGrid?
3
1167
by: Engineerik | last post by:
The vb6 datagrid had a "button" property which I used to display a dropdown icon in a cell. I created a popup menu that would display the list of valid choices for that cell when the user clicked the dropdown icon. In vb.net I havn't been able to figure out how to display that little dropdown icon in a datagrid cell. Anybody know how to display the dropdown icon in the datagrid and the best way to display a list of valid entries which the...
4
7630
by: Peter | last post by:
(VS 2003) I have a DataGrid and accept button. My problem is when a user starts to edit one of the values in the grid and does not either press Enter or move of the current cell and presses the Accept buton the current typed value does not get passed into the grid, but stays in the edit mode. How can I move the current edit value into the grid without requireing user to press Enter or move to a different cell? Thanks
0
1428
by: anjupt | last post by:
Hi, I can add values to a dropdown from 1 to 100 using a while loop in page load.ie Dim i = 1 While i <= 100 Me.DropDownList2.Items.Add(i) ' i = i + 1 End While this code if written in page load gives out a dropdown consisting of numbers 1 to 100 on execution of the page ..
9
2734
by: rn5a | last post by:
A Form has a DataGrid which displays records from a SQL Server 2005 DB table. Users can modify the records using this DataGrid for which I am using EditCommandColumn in the DataGrid. This is the code: <script runat="server"> Dim sqlConn As New SqlConnection(".....") Sub Page_Load(ByVal obj As Object, ByVal ea As EventArgs) If Not (Page.IsPostBack) Then FillDataGrid()
0
9856
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9698
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,...
0
10916
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
10598
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
10657
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
10299
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
7836
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
5684
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...
0
5872
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.