Hullo there,

C#Net 2003 Window Application
I need your help again.

I am trying to loop through the DataGrid rows and confirm that FirstColumn which hold Checkbox is TRUE. If it's TRUE, I need to retrieve the Customer FirstName(2nd Column) and LastName (3rd Column) and transfer the data onto WORD LETTER TEMPLATE for printing.

I wrote this script and it's completely wrong:

private void BtnSelectRow(object sender, System.EventArgs e)
{
     foreach (datarow DR in this.DataGrid1)
       {
            if ( DR.Column(0).checked == true )
                  strFName = DR.Cell(1).text;
                 strLName = DR.Cell(2).text;
       }
}

I need your help. Please Help me. Thanks

Rather than trying to iterate through the datagrid's rows, use the underlying datasource:

foreach (DataRow dr in ((DataTable)dataGrid1.DataSource).Rows)
            {
                if ((bool)dr[0])
                {
                    strFName = dr[1].ToString();
                    strLName = dr[2].ToString();
                }
            }

Hi there,

I tried out the suggestion and the compilation generated this error message list below

foreach statement cannot operate on variables of type 'System.Windows.Forms.DataGrid' because 'System.Windows.Forms.DataGrid' does not contain a definition for 'GetEnumerator', or it is inaccessible

Hi there,

I tried out the suggestion and the compilation generated this error message list below

foreach statement cannot operate on variables of type 'System.Windows.Forms.DataGrid' because 'System.Windows.Forms.DataGrid' does not contain a definition for 'GetEnumerator', or it is inaccessible

You got that error trying out the code i gave you?

Are you sure you used the code exactly as i gave it to you? That error would suggest you are trying something like foreach(DataRow dr in this.dataGrid1) .
You need to retrieve the underlying datasource this.dataGrid1.DataSource , as this returns an object you need to cast it to a usable type, in this case a datatable (DataTable)this.dataGrid1.DataSource . Once you have the datatable, you can iterate through each of the rows in its .Rows member: ((DataTable)dataGrid1.DataSource).Rows .
If it helps, you can split this line down into its parts like this:

string strFName, strLName;

            DataTable gridSource = (DataTable)dataGrid1.DataSource;

            foreach (DataRow dr in gridSource.Rows)
            {
                if ((bool)dr[0])
                {
                    strFName = dr[1].ToString();
                    strLName = dr[2].ToString();
                }
            }

Hi Ryshad
I have changed my existing script to incorporate your new suggestion and this the compilaton error list below is caused by this portion of script

[ if ( ( bool) dr[0])

Compilation Error message:-
An unhandled exception of type 'System.InvalidCastException' occurred in CSharpNet2003DataGrid.exe
Additional information: Specified cast is not valid.

Here is my script.

private void BtnDisplaySelection_Click(object sender, System.EventArgs e)
{
   String strFName; strLName = "";
   String strDisplayName = "";

   DataTable gridSource = (DataTable) dataGrid1.DataSource;
   foreach (DataRow dr in gridSource.Rows)
      {
	if ( ( bool) dr[0])		
	   {		
	       strFName = dr[1].ToString() ;
	       strLName = dr[2].ToString() ;

     	      strDisplayName += strFName + " " + strLName + '\n';
	      strFName = "";
	      strLName = "";
                }
	
	if ( strDisplayName.Length != 0 )
                 {
		txtSelection.Text = strName.ToString();
	   }
       } 
}

Thank you for your suggestion and sharing your knowledge with me.
I am using C#.NET Window application.

Upload a sample of your project, or at the very least post the designer and code file for the form in question. There are a lot of things that can go wrong, by simply being different, in grid setups. I have a similar project and this iterates through all of the rows to see if all of the rows have been selected:

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
    {
      if (suspendEvents)
        return;

      if (e.ColumnIndex == 0)
      {
        bool allChecked = true;


        for (int i = 0; i < this.dataGridView1.RowCount; i++)
        {
          if (this.dataGridView1.Rows[i].IsNewRow)
            continue;

          bool colChecked = string.Compare(this.dataGridView1.Rows[i].Cells[0].EditedFormattedValue.ToString(), "true", true) == 0;
          if (i == e.RowIndex)
            colChecked = !colChecked; //Active row hasn't updated underlying data yet

          if (!colChecked)
          {
            allChecked = false;
            break;
          }
        }

        if (allChecked)
        {
          suspendEvents = true;
          try
          {
            colHead.CheckAll = true;
            dataGridView1.InvalidateColumn(0);
          }
          finally
          {
            suspendEvents = false;
          }
        }
      }
    }

You will also see some other odd behavior with the gridview which is why I asked for code. For example if you run this code on the "CellClick" event then this will fire before the underlying value has been updated so you either need to force the grid to update the underlying data or negate the value of the checked column.

Hi Sknake,
Thank you for your sample script. Although your script is C#.NET 2005 , I will try to make some changes to it to suit C#.NET 2003. In C#.NET 2003 window application only DataGrid is valid name and not DataGridView.

Here are the script which create a column in the DataTable

[B]private void FLoadDataGrid()[/B]{
DataTable DT = new DataTable();
DataColumn colNewDGCol = new DataColumn();
colNewDGCol.DataType = System.Type.GetType("System.Boolean");
colNewDGCol.DefaultValue = false;
colNewDGCol.ColumnName = ("Selected");
DT.Columns.Add(colNewDGCol);
			 		 
//... file datagrid
FFormatDataGridColumn();
dataGrid1.DataSource = DT; 
}
[B]private void FFormatDataGridColumn()[/B]
{
//checkbox column
DataGridBoolColumn chkboxCol = new DataGridBoolColumn();
chkboxCol.MappingName = "Selected";
chkboxCol.HeaderText = "";
chkboxCol.Width = 50;
DGStyle.GridColumnStyles.Add(chkboxCol);
}

//--------------------------------------
this script to retrieve firstname and lastname depending on checkbox = true
When checkbox in(column(0)) is checked, it does not update the underlying table.

private void BtnDisplaySelection_Click(object sender, System.EventArgs e)
{
  String strFName= "";		
  String strName = "";				 

  DataTable gridSource = (DataTable) dataGrid1.DataSource;
   foreach ( DataRow dr in gridSource.Rows)
	{		 				
   	strFName = dr[1].ToString() + dr[2].ToString() + '\n';	 	strName += strFName;
	strFName = "";		 				}	 
			  		 
	if ( strName.Length != 0 )
	  {
                     txtSelection.Text = strName.ToString();
	  }
} // end private

Hmm, i cant see where you are getting the names from : / according to your code you are creating the datagrid with a single checkbox column.

Im not sure why your cast is failing, insert a breakpoint and check the contents of 'dr' and 'dr[0]' to see if your datatable is returning the expected values.

Also, try using column names instead of index numbers like (bool)dr["Selected"] Lastly, the last code you posted has nothing in it to check if the checkbox has been ticked...
Your code takes the values from columns 1 and 2 (which dont exist unless they are added outside the code you posted), concatenates them together with a newline character and assigns it to your textbox. But each row overwrites the textbox. The result is that whatever checkboxes you have ticked the textbox will always contain the value of the last row.

Hi RySHAD,
Thank you very much for sharing your knowledge with me. Based on your suggestion, ((bool) dr["Selected"]), my progams is now working. You are just awesome.

I am sharing the script listed below with other Newbies using C#.NET 2003.

Thank you very much for helping me.

[B]private void FFormatDataGridColumn[/B]()
   //define column structure for datagrid
  {
// declare tablestyle
DataGridTableStyle DGStyle;	 
DGStyle = new DataGridTableStyle();	 
DGStyle.MappingName = "PatientTbl";		 

//checkbox column
  DataGridBoolColumn chkboxCol = new   dataGridBoolColumn();
  chkboxCol.MappingName = "Selected";
 chkboxCol.HeaderText = "";
 chkboxCol.Width = 50;
DGStyle.GridColumnStyles.Add(chkboxCol);

//PatientId TextBox Column
 DataGridColumnStyle colPatientID = new d ataGridTextBoxColumn);
colPatientID.MappingName = "PatientId";
colPatientID.HeaderText  ="Patient ID";
colPatientID.Width = 70;	
colPatientID.ReadOnly = true;
DGStyle.GridColumnStyles.Add(colPatientID);

//Firstname textbox column
DataGridColumnStyle colFName = new DataGridTextBoxColumn();
colFName.MappingName = "FirstName";
colFName.HeaderText = "First Name";
colFName.Width = 150;
colFName.ReadOnly = true;
DGStyle.GridColumnStyles.Add(colFName);

//lastName textbox column
 DataGridColumnStyle colLName = new DataGridTextBoxColumn();
colLName.MappingName = "LastName";
colLName.HeaderText = "Last Name";
colLName.Width = 150;
colLName.ReadOnly = true;
DGStyle.GridColumnStyles.Add(colLName);
	

// add table style to the dataGrid
this.dataGrid1.TableStyles.Add(DGStyle);		
} 


//------------------------------------------------------------------
private void FLoadDataGrid()
{
      string strSql = "Select  PatientId, FirstName, LastName from TblPatient ";    
sqlConn = new SqlConnection(connStr);
sqlConn.Open();
DA = new SqlDataAdapter(strSql, sqlConn);
DS =   new DataSet("DS");

//Clear dataset before refill 
DS.Clear();
DS.CaseSensitive = true;
DA.Fill(DS,"PatientTbl");

//declare datatable
DataTable DT = new DataTable();
DT.Clear();
DT = DS.Tables[0];
            
DataColumn colNewDGCol = new DataColumn();
colNewDGCol.DataType = System.Type.GetType("System.Boolean");
colNewDGCol.DefaultValue = false;
colNewDGCol.ColumnName = ("Selected");
DT.Columns.Add(colNewDGCol);
	 		 
//... file datagrid
FFormatDataGridColumn();
dataGrid1.DataSource = DT; 		 
sqlConn.Close();
		    
} // end private

//-------------------------------------------------------------------------
private void BtnDisplaySelection_Click(object sender, System.EventArgs e)
{	 
             String strFName= "";		
	String strName = "";				 
              DataTable gridSource = (DataTable) dataGrid1.DataSource;
             foreach ( DataRow dr in gridSource.Rows)
	{	
	if ((bool)dr["Selected"])
                  {	 				
	strFName = dr[1].ToString() + dr[2].ToString() + '\n'
                 strName += strFName;
	strFName = "";	
                 }
}						

// display on textbox to prove it working			  if ( strName.Length != 0 )
   {
      txtSelection.Text = strName.ToString();
  }
} // end private

No problem, i'm glad its all working now :)

Hi Ryshad,
I am so glad that I met you at this FORUM.
You are so generous to share your knowledge.
Which country are you from?
I was from Malaysia now living in New Zealand.

Hi Ryshad,
I am so glad that I met you at this FORUM.
You are so generous to share your knowledge.
Which country are you from?
I was from Malaysia now living in New Zealand.

Haha, im blushing!! It's no problem, really. I enjoy problem solving, and i like helping people. Helping out here at Daniweb is like solving a sudoku that says thank you when your done :)

I'm from the UK. I graduated last year so this is a great way to keep everything fresh and to help me improve my own knowledge in some areas.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.