Wrox Programmer Forums
Go Back   Wrox Programmer Forums > .NET > Other .NET > General .NET
|
General .NET For general discussion of MICROSOFT .NET topics that don't fall within any of the other .NET forum subcategories or .NET language forums.  If your question is specific to a language (C# or Visual Basic) or type of application (Windows Forms or ASP.Net) try an applicable forum category. ** PLEASE BE SPECIFIC WITH YOUR QUESTION ** When posting here, provide details regarding the Microsoft .NET language you are using and/or what type of application (Windows/Web Forms, etc) you are working in, if applicable to the question. This will help others answer the question without having to ask.
Welcome to the p2p.wrox.com Forums.

You are currently viewing the General .NET section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
 
Old July 5th, 2004, 08:36 AM
Authorized User
 
Join Date: Jun 2004
Posts: 18
Thanks: 0
Thanked 0 Times in 0 Posts
Default DataGrid and DataKeys Problem

OK this might seem I pretty dumb question and to be honest I think of myself as a pretty dumb guy, but hey, I'm new to .NET (one week and counting) and this is my very first DataGrid and the work is due next week so here I go asking this question.
Here it is (my question). I only hope I'm in the right forum.

All I an trying to do is 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("");

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>
 
Old July 5th, 2004, 04:25 PM
Friend of Wrox
 
Join Date: Oct 2003
Posts: 336
Thanks: 0
Thanked 0 Times in 0 Posts
Send a message via MSN to alyeng2000
Default

as i mean
there is no confuse between datakey for the grid and columns displayed
make two template columns one for id and one for customer

Ahmed Ali
Software Developer
 
Old July 5th, 2004, 10:02 PM
planoie's Avatar
Friend of Wrox
 
Join Date: Aug 2003
Posts: 5,407
Thanks: 0
Thanked 16 Times in 16 Posts
Default

The intent of the DataKeys attribute of the datagrid is not really to serve as a source of the data for further use. It's intended to be used to hold a key piece of data so that you can use that to further query the data when you want to deal with a specific row of the grid data which is what you are trying to achieve. What you might want to try is this: in your handler for the grid's selectedIndexChanged event, use the event args object (e) and look into the "Item" property on that. This will be a DataGridItem object. On that object you can access the cells of the datagrid and thereby get at all the data that you can see in the grid.
 
Old July 6th, 2004, 10:32 AM
Authorized User
 
Join Date: Jun 2004
Posts: 18
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Hey thanks,I took a look at the selectedIndexChanged event but there did not seem to be an Item property (unless I'm looking in the wrong place). So there's no way to get two parameters into GetSelections_Click which would represent ID and also Customer? You are exactly correct that what I am trying to do is to hold a key piece of data so that you can use that to further query the data when you want to deal with a specific row of the grid data - just that I want to hold onto two pieces of data. The idea is that I would use the selected values to then build a SQL query.
 
Old July 6th, 2004, 11:10 AM
planoie's Avatar
Friend of Wrox
 
Join Date: Aug 2003
Posts: 5,407
Thanks: 0
Thanked 16 Times in 16 Posts
Default

My bad. I got my events mixed up. SelectedIndexChanged is inherited from the BaseDataList class. That only passes a standard EventArgs to the event.

What you can do is access the grid's SelectedItem, then you can access the cells from that property.

Sorry for the confusion.





Similar Threads
Thread Thread Starter Forum Replies Last Post
datagrid problem?? piyushktyagi ADO.NET 0 April 18th, 2007 09:07 AM
DataKeys to update and delete data in DataGrid D86j ASP.NET 1.0 and 1.1 Basics 4 January 9th, 2007 11:35 AM
Problem with datagrid Shishir ASP.NET 1.0 and 1.1 Professional 1 January 6th, 2007 09:01 AM
Datagrid problem torsch VB.NET 2002/2003 Basics 3 September 4th, 2006 10:41 AM
Datagrid problem dotnetprogrammer VS.NET 2002/2003 1 February 17th, 2005 05:11 AM





Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.