473,386 Members | 1,969 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

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
SQL

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="customer"
Font-Size="XX-Small">

and then

gridSelections.AppendFormat("{0} ",

DemoGrid.DataKeys[DemoGridItem.ItemIndex].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="id"
Font-Size="XX-Small">

will result the id field being in the result of

gridSelections.AppendFormat("{0} ",

DemoGrid.DataKeys[DemoGridItem.ItemIndex].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.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;
using System.Data.SqlClient;
using System.Text;

namespace WebApplication1

{

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

public class WebForm1 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.DataGrid DemoGrid;
protected System.Web.UI.WebControls.Label ResultsInfo;
protected System.Web.UI.WebControls.Button GetSelections;

private void Page_Load(object sender, System.EventArgs e)
{
if(!IsPostBack)
{
//Create a SqlConnection object.
//Modify the connection string as necessary for your environment.
SqlConnection cn = new
SqlConnection("Server=MyServer;database=MyDatabase ;UID=sa;PWD=MyPassword
");
SqlCommand cmd = new SqlCommand("SELECT Field_ID as ID, Field_Customer
as Customer FROM Table_Customer",cn);
cn.Open();
SqlDataReader reader = cmd.ExecuteReader();
DemoGrid.DataSource = reader;

DataBind();
reader.Close();
cn.Close();
}
}

#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.DemoGrid.SelectedIndexChanged += new
System.EventHandler(this.DemoGrid_SelectedIndexCha nged);
this.GetSelections.Click += new
System.EventHandler(this.GetSelections_Click);
this.Load += new System.EventHandler(this.Page_Load);
}

#endregion
private void GetSelections_Click(object sender, System.EventArgs e)
{
int rowCount = 0;
StringBuilder gridSelections = new StringBuilder();
//Loop through each DataGridItem, and determine which CheckBox controls
//have been selected.
foreach(DataGridItem DemoGridItem in DemoGrid.Items)
{
CheckBox myCheckbox = (CheckBox)DemoGridItem.Cells[0].Controls[1];
if(myCheckbox.Checked == true)
{
rowCount++;
gridSelections.AppendFormat("{0} ",
DemoGrid.DataKeys[DemoGridItem.ItemIndex].ToString());

ListBox myListBox = (ListBox)DemoGridItem.Cells[1].Controls[1];
gridSelections.AppendFormat( " " +
myListBox.SelectedItem.Text.ToString()+ " <br>");
}
} gridSelections.Append("<hr>");

gridSelections.AppendFormat("Total number selected is: {0}",
rowCount.ToString());

ResultsInfo.Text = gridSelections.ToString();
}
private void DemoGrid_SelectedIndexChanged(object sender,
System.EventArgs e)
{
}

public SqlDataReader GetReportNames ()
{

//Polulates the list box for report names
SqlConnection conn = new SqlConnection("server=MyServer; uid=sa;
pwd=MyPassword; Database=MyDatabase");
String sqlConnection = "select Report, Name from TableReports";
SqlCommand sqlCommand = new SqlCommand(sqlConnection, conn);
conn.Open();
SqlDataReader sqlDataReader;
sqlDataReader = sqlCommand.ExecuteReader();
return sqlDataReader;
sqlDataReader.Close();
conn.Close();
}
}
}
HTML WebForm
============

<%@ Page language="c#" Codebehind="WebForm1.aspx.cs"
AutoEventWireup="false" Inherits="WebApplication1.WebForm1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>WebForm1</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 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="customer"
Font-Size="XX-Small">
<Columns>
<asp:TemplateColumn HeaderText="Run">
<ItemTemplate>
<asp:CheckBox ID="myCheckbox" Runat="server" />
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Report">
<ItemTemplate>
<asp:ListBox ID="myListbox" Rows="1" Width="150px"
SelectionMode="Single" Runat="server"
DataSource = "<%# GetReportNames() %>"
DataTextField="ReportName" DataValueField="Report" />
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:datagrid><asp:button id="GetSelections" style="Z-INDEX: 102;
LEFT: 472px; POSITION: absolute; TOP: 24px"
runat="server" Text="Build Request"
Width="152px"></asp:button></form>
</body>
</HTML>

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

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 categoryDescription;
TextBox tb;
tb = (TextBox) e.Item.Cells[2].Controls[0];
categoryName = tb.Text;
tb = (TextBox) e.Item.Cells[3].Controls[0];
categoryDescription = tb.Text

Nov 16 '05 #2

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

Similar topics

2
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...
0
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...
5
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...
1
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...
4
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...
9
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: ...
4
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...
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...
9
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...
2
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...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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
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,...
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...

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.