473,734 Members | 2,724 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

DataGrid Problem

I am trying display the contents of a table in a web page, select
certain rows from that table and then display the fields that I have
selected (now table columns) as text in a Label object. Amazingly I have
managed to display the table - no problem, I can select rows - no
problem, BUT I can't work out how to display more than one of the fields
(now columns in the table in the web page). I can display one field OK,
but not more than one field and its driving me bonkers. All of my
confusion is related to how you reference a DataKeyField in a DataGrid.

The two fields that I am selecting are ID and a Customer taken from the

SELECT Field_ID as ID, Field_Customer as Customer FROM Table_Customer

I've worked out that the DataGrid DataKeys property (if it is a
property) controls which field is passed to the the instance of the
DataGrid so

<asp:datagrid id="DemoGrid" runat="server" DataKeyField="c ustomer"

and then

gridSelections. AppendFormat("{ 0} ",

DemoGrid.DataKe ys[DemoGridItem.It emIndex].ToString());

will result in the customer field being in the result

and if I change the DataKeyField to id then

<asp:datagrid id="DemoGrid" runat="server" DataKeyField="i d"

will result the id field being in the result of

gridSelections. AppendFormat("{ 0} ",

DemoGrid.DataKe ys[DemoGridItem.It emIndex].ToString());

Thing is I want both customer and id to be in the result.

There that is my problem (well the real problem is lack of knowledge of
DataGrids and C# in general - but thats my problem).

I hope the question makes sense and if I have offended anyone with the
question I apologize but suggest you try to take it easy.

Here's the complete c# code behind the scene and also the HTML code of
the web form.

Other than begging and pleading HELP , I would be very grateful if
someone could shine light upon the darkness of my ignorance.

WebForm1.aspx.c s
=============== =

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;
using System.Text;

namespace WebApplication1


/// <summary>
/// Summary description for WebForm1.
/// </summary>

public class WebForm1 : System.Web.UI.P age
protected System.Web.UI.W ebControls.Data Grid DemoGrid;
protected System.Web.UI.W ebControls.Labe l ResultsInfo;
protected System.Web.UI.W ebControls.Butt on GetSelections;

private void Page_Load(objec t sender, System.EventArg s e)
//Create a SqlConnection object.
//Modify the connection string as necessary for your environment.
SqlConnection cn = new
SqlConnection(" Server=MyServer ;database=MyDat abase;UID=sa;PW D=MyPassword
SqlCommand cmd = new SqlCommand("SEL ECT Field_ID as ID, Field_Customer
as Customer FROM Table_Customer" ,cn);
SqlDataReader reader = cmd.ExecuteRead er();
DemoGrid.DataSo urce = reader;


#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();

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeCompo nent()
this.DemoGrid.S electedIndexCha nged += new
System.EventHan dler(this.DemoG rid_SelectedInd exChanged);
this.GetSelecti ons.Click += new
System.EventHan dler(this.GetSe lections_Click) ;
this.Load += new System.EventHan dler(this.Page_ Load);

private void GetSelections_C lick(object sender, System.EventArg s e)
int rowCount = 0;
StringBuilder gridSelections = new StringBuilder() ;
//Loop through each DataGridItem, and determine which CheckBox controls
//have been selected.
foreach(DataGri dItem DemoGridItem in DemoGrid.Items)
CheckBox myCheckbox = (CheckBox)DemoG ridItem.Cells[0].Controls[1];
if(myCheckbox.C hecked == true)
gridSelections. AppendFormat("{ 0} ",
DemoGrid.DataKe ys[DemoGridItem.It emIndex].ToString());

ListBox myListBox = (ListBox)DemoGr idItem.Cells[1].Controls[1];
gridSelections. AppendFormat( " " +
myListBox.Selec tedItem.Text.To String()+ " <br>");
} gridSelections. Append("<hr>");

gridSelections. AppendFormat("T otal number selected is: {0}",
rowCount.ToStri ng());

ResultsInfo.Tex t = gridSelections. ToString();
private void DemoGrid_Select edIndexChanged( object sender,
System.EventArg s e)

public SqlDataReader GetReportNames ()

//Polulates the list box for report names
SqlConnection conn = new SqlConnection(" server=MyServer ; uid=sa;
pwd=MyPassword; Database=MyData base");
String sqlConnection = "select Report, Name from TableReports";
SqlCommand sqlCommand = new SqlCommand(sqlC onnection, conn);
SqlDataReader sqlDataReader;
sqlDataReader = sqlCommand.Exec uteReader();
return sqlDataReader;
sqlDataReader.C lose();
HTML WebForm

<%@ Page language="c#" Codebehind="Web Form1.aspx.cs"
AutoEventWireup ="false" Inherits="WebAp plication1.WebF orm1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<title>WebForm1 </title>
<meta content="Micros oft Visual Studio .NET 7.1" name="GENERATOR ">
<meta content="C#" name="CODE_LANG UAGE">
<meta content="_JavaS cript" name="vs_defaul tClientScript">
<meta content="http://schemas.microso ft.com/intellisense/ie5"
name="vs_target Schema">
<body MS_POSITIONING= "GridLayout ">
<form id="Form1" method="post" runat="server">
<asp:label id="ResultsInfo " style="Z-INDEX: 103; LEFT: 472px;
POSITION: absolute; TOP: 112px"
runat="server" Width="304px" Height="112px"> </asp:label>
<asp:datagrid id="DemoGrid" runat="server" DataKeyField="c ustomer"
<asp:TemplateCo lumn HeaderText="Run ">
<ItemTemplate >
<asp:CheckBox ID="myCheckbox " Runat="server" />
</asp:TemplateCol umn>
<asp:TemplateCo lumn HeaderText="Rep ort">
<ItemTemplate >
<asp:ListBox ID="myListbox" Rows="1" Width="150px"
SelectionMode=" Single" Runat="server"
DataSource = "<%# GetReportNames( ) %>"
DataTextField=" ReportName" DataValueField= "Report" />
</asp:TemplateCol umn>
</asp:datagrid><a sp:button id="GetSelectio ns" style="Z-INDEX: 102;
LEFT: 472px; POSITION: absolute; TOP: 24px"
runat="server" Text="Build Request"

*** Sent via Devdex http://www.devdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 16 '05 #1
1 2522

Here is a way that you can read the contents of cells from a datagrid. This assumes that you are displaying the data in TextBoxes. You would have to adjust the code if you are using a different type of control or not control at all. I hope this helps. Cheers, Danny!
string categoryName;
string categoryDescrip tion;
TextBox tb;
tb = (TextBox) e.Item.Cells[2].Controls[0];
categoryName = tb.Text;
tb = (TextBox) e.Item.Cells[3].Controls[0];
categoryDescrip tion = tb.Text

Nov 16 '05 #2

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

Similar topics

by: Chris Plowman | last post by:
Hi all, I was wondering if anyone can help me with a really annoying problem I have been having. I made a derived datagrid class that will select the row when a user clicks anywhere on a cell (multi-select without modifier keys). I got that working fine, but I also wanted to keep rows selected after a sort, which I do by storing the row's id in an arraylist. The idea was to do the sort and then go back and re-select the rows with that...
by: Emerson | last post by:
The following assumes a System.Windows.Forms.DataGrid with a System.Data.DataTable set as the DataSource. I'm programming in C# Here's my scenario I click in a cell on a DataGrid. I enter some text. Before changing to another cell in the DataGrid, I move my mouse pointer off the DataGrid and change the selected item in a ListBox or TreeView. Here's my question Which should fire first, the DataTable's RowChanged/CellChanged event or...
by: Jeff | last post by:
IDE: VS 2003 :NET OS: XP Pro My app have a form with a tab-control on it. The tab-control have 2 tabpages. One of the tabpages displays a datagrid, and the other tabpage displays details (order date, name, address etc) about the selected row in the datagrid... My problem is when I enter a new record in the details tabpage (saves data to database), and go back to the datagrid. Only the data from the PM-table
by: Rick | last post by:
Hello all, I hope all is well with you. I am having a seriously difficult time with this problem. Allow me to set up the problem. I have a System.Web.UI.Page with the following controls (watch the layout, some have child controls):
by: The Alchemist | last post by:
I am having a problem with a dynamically-generated Datagrid. It is important to point out that this problem does not exist with a design-time created Datagrid, but only with a dynamically generated Datagrid in a Web Custom Control (WCC) : The datagrid has LinkButton Column which has a select LinkButton for each row. When this button is clicked, the Datagrid raises its 'ItemCommand' event which captures the information for that row and...
by: tshad | last post by:
How do I find (and set) a couple of labels in the Footer after a DataGrid is filled? I have a bunch of DataGrids that get displayed nested inside a DataList. The datagrid looks like: ******************************************************************************* <asp:DataGrid visible="False" border=1
by: tshad | last post by:
I am having trouble with links in my DataGrid. I have Links all over my page set to smaller and they are consistant all over the page in both Mozilla and IE, except for the DataGrid. Here is a snippet from my .css file: *************************** body { margin:0; padding:0;
by: optimizeit | last post by:
What I am attempting to do is import an Excel Workbook and display the worksheets in a datagrid dynamically. I am very close to getting this to work. I have to this point successfully imported a single worksheet into a dataset. I successfully built a dynamic datagrid. And I did successfully bind it to the dataset. Then I added the datagrid control to a PlaceHolder. The first worksheet displays beautifully. The next step is to allow...
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()
by: =?Utf-8?B?Y3JlYXZlczA2MjI=?= | last post by:
I have a nested datagrid in a xaml file, the parent datagrid loads the vendor information and the details loads the documents for that vendor in a datagrid. Everything is working fine until I click in the child datagrid and then go to the combobox and choose another vendor. When the new vendor is loaded nothing shows in the datagrid but the itemsource shows the info is there. Know if I click on the child cell and then click back on the...
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...
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,...
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...
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,...
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...
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...
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();...
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
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.