?
Solved

Get the value of column "ID" from the GridViewRow

Posted on 2012-08-25
15
Medium Priority
?
3,223 Views
Last Modified: 2012-08-27
Hello,

How do I get the value of column "ID" from the GridViewRow.

Thank you!

     int i = 0;
            string aVar = "";

           foreach (GridViewRow gr in GridView1.Rows)
            {
                CheckBox cb = (CheckBox)gr.Cells[1].FindControl("CheckBox1");
                if (cb.Checked == false)
                {
                    gr.Visible = false;
                }
                else
                {
                    aVar = GridView1.Rows[GridView1.SelectedRow[0].Cells["ID"].Value.ToString();   

                   if (myVar == null)
                   {
                       myVar = aVar;
                   }
                   else
                   {
                       myVar = myVar + "," + aVar;
                   }
                
                   i++;
                }

Open in new window

0
Comment
Question by:Rad1
  • 6
  • 6
  • 3
15 Comments
 
LVL 20

Assisted Solution

by:informaniac
informaniac earned 668 total points
ID: 38331985
gr.Cells[0].Text;

You need to provide the index of the ID column.
0
 

Author Comment

by:Rad1
ID: 38332016
I have the I need to get the the ID from the row so I can query the database by the ID that I get back from the row.

How do I use gr.Cells[0].Text; in the
GridView1.Rows[GridView1.SelectedRow[0].Cells["ID"].Value.ToString();  

Open in new window

0
 

Author Comment

by:Rad1
ID: 38332032
By the way, I want to get the value of column ID from Gridview Rowindex, is it possible?
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 20

Assisted Solution

by:informaniac
informaniac earned 668 total points
ID: 38332439
Is ID a column of the Gridview?

In your code you are looping through the Gridview rows

foreach (GridViewRow gr in GridView1.Rows)
 {
             
}

So if your ID column is first column in your gridview then you will get the value of ID column by using

gr.Cells[0].Text;

Is this what you want?
0
 
LVL 26

Assisted Solution

by:Alan Warren
Alan Warren earned 1332 total points
ID: 38333053
Hi Rad1,
not sure where you are invoking your code from, which event?
I tested this VB code using the On_RowCommand event.
You will find a C version of how to get the index of a gridview column by name on this page:
http://forums.asp.net/p/1076872/1584635.aspx

I just modified it a bit to suit your needs.

Protected Sub gv_RowCommand(sender As Object, e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gv.RowCommand
    
    ' get the commandargument
    Dim index As Integer = Convert.ToInt32(e.CommandArgument)
    
    ' Retrieve the row selected by the user from the Rows collection.
    Dim row As GridViewRow = sender.Rows(index)
    
    ' Get the index of the "ID" column by Name
    Dim strColumnName As String = "ID"
    Dim columnIndex As Integer = -1
    For Each field As DataControlField In gv.Columns
      If TypeOf field Is System.Web.UI.WebControls.BoundField Then
        If CType(field, BoundField).DataField = strColumnName Then
          columnIndex = gv.Columns.IndexOf(field)
        End If
      End If
    Next
    
    ' Print the value of the ID column for the selected row
    System.Diagnostics.Debug.Print(gv.Rows(index).Cells(columnIndex).Text.ToString())

End Sub

Open in new window

Alan
0
 

Author Comment

by:Rad1
ID: 38333057
Thank you all!

Yes the I'd is the first column but I tried gr.cells and I did not get anyti.  I got nul???
0
 

Author Comment

by:Rad1
ID: 38333183
I am using the code in Button event:
Any idea why????

        protected void Button1_Click(object sender, EventArgs e)
        {
            int i = 0;
            string aVars = "";

           foreach (GridViewRow gr in GridView1.Rows)
            {
                CheckBox cb = (CheckBox)gr.Cells[1].FindControl("CheckBox1");
                if (cb.Checked == false)
                {
                    gr.Visible = false;
                }
                else
                {
                  
                    aVars = gr.Cells[0].Text;   // I am getting  NULL here

                   if (theVar == null)
                   {
                       theVar = aVar;
                   }
                   else
                   {
                       theVar = theVar + "," + aVar;
                   }
                
                   i++;
                }
                Session["rowIndexes"] = myVar;
            }
        }

Open in new window

0
 
LVL 26

Assisted Solution

by:Alan Warren
Alan Warren earned 1332 total points
ID: 38333356
Hi Rad1,

The following VB code, invoked by a button_click, will get the value from the column bound to the field named "ID" for  the selected row of a gridview named gv.

Sorry about it being in VB syntax.
Protected Sub Button1_Click(sender As Object, e As System.EventArgs)
    
     
    Dim index As Int32 = gv.SelectedIndex
    
    If index < 0 Then
      ' nothing selected
      Exit Sub
    End If
    
    ' Retrieve the row selected by the user from the Rows collection.
    Dim row As GridViewRow = gv.Rows(index)
    
    Dim strColumnName As String = "ID"
    Dim columnIndex As Integer = -1
    For Each field As DataControlField In gv.Columns
      If TypeOf field Is System.Web.UI.WebControls.BoundField Then
        If CType(field, BoundField).DataField = strColumnName Then
          columnIndex = gv.Columns.IndexOf(field)
        End If
      End If
    Next
    
    If columnIndex < 0 Then
      ' no column found by that name
      Exit Sub
    End If
    
    Dim intID As Int32 = gv.Rows(index).Cells(columnIndex).Text
    
    ' Populate some var with intID 
    Me.Page.Title = "The ID column value for the selected row is " & intID.ToString
    

  End Sub

Open in new window

0
 
LVL 26

Assisted Solution

by:Alan Warren
Alan Warren earned 1332 total points
ID: 38333473
Hi Rad1,
Cool tool:
  -- Download the demo version and use the 'Snippet' convertor.
Instant C# – VB to C# Converter
http://www.tangiblesoftwaresolutions.com/Product_Details/Instant_CSharp.html

using System;

protected void Button1_Click(object sender, System.EventArgs e)
{


	Int32 index = gv.SelectedIndex;

	if (index < 0)
	{
	  // nothing selected
	  return;
	}

	// Retrieve the row selected by the user from the Rows collection.
	GridViewRow row = gv.Rows[index];

	string strColumnName = "ID";
	int columnIndex = -1;
	foreach (DataControlField field in gv.Columns)
	{
	  if (field is System.Web.UI.WebControls.BoundField)
	  {
		if (((BoundField)field).DataField == strColumnName)
		{
		  columnIndex = gv.Columns.IndexOf(field);
		}
	  }
	}

	if (columnIndex < 0)
	{
	  // no column found by that name
	  return;
	}

	Int32 intID = Convert.ToInt32(gv.Rows[index].Cells[columnIndex].Text);

	this.Page.Title = "The ID column value for the selected row is " + intID.ToString();

	// Print the value of the ID column for the selected row
	System.Diagnostics.Debug.Print(gv.Rows[index].Cells[columnIndex].Text.ToString());

  }

Open in new window

Alan ";0)
0
 
LVL 26

Accepted Solution

by:
Alan Warren earned 1332 total points
ID: 38333536
Hi rad1,
you've got me writing C# now, arrgghh.

ps.. that Download the demo version in the previous post ain't so cool, it only works one time, unless you buy it, hmmm.


 protected void Button1_Click(object sender, EventArgs e)
  {

    int i = 0;
    string aVar = "";
    // these variables did not exist in the current context
    string myVar = "";

    foreach (GridViewRow gr in GridView1.Rows)
    {
      CheckBox cb = (CheckBox)gr.Cells[1].FindControl("CheckBox1");
      if (cb.Checked == false)
      {
        gr.Visible = false;
      }
      else
      {
        // aVar = gr.Cells[0].Text;   // I am getting  NULL here


        string strColumnName = "ID";
        int columnIndex = -1;
        foreach (DataControlField field in GridView1.Columns)
        {
          if (field is System.Web.UI.WebControls.BoundField)
          {
            if (((BoundField)field).DataField == strColumnName)
            {
              columnIndex = GridView1.Columns.IndexOf(field);
            }
          }
        }

        if (columnIndex < 0)
        {
          // no column found by that name
          return;
        }

        aVar = gr.Cells[columnIndex].Text;   // I was getting  NULL here       

        if (myVar == null)   // myVar did not exist in the current context
        {
          myVar = aVar;
        }
        else
        {
          myVar = myVar + "," + aVar;
        }

        i++; // unused variable
      }
    }
}

Open in new window

0
 
LVL 20

Assisted Solution

by:informaniac
informaniac earned 668 total points
ID: 38333604
Alternatively you could use the DataKeyNames property of GridView.

<asp:GridView id="GridView1" runat="server" DataKeyNames="ID"....

GridView1.DataKeys[gr.RowIndex].Value.ToString();
0
 
LVL 26

Assisted Solution

by:Alan Warren
Alan Warren earned 1332 total points
ID: 38333626
If no datakeys are defined:

  protected void Button1_Click(object sender, System.EventArgs e)
  {

	string aVar = "";
	string strColumnName = "ID";
	int columnIndex = -1;
	GridViewRow row = null;

	foreach (GridViewRow gr in GridView1.Rows)
	{
	  CheckBox cb = (CheckBox)(gr.Cells[1].FindControl("CheckBox1"));
	  if (cb.Checked == false)
	  {
		gr.Visible = false;
	  }
	  else
	  {

		// only loop columns for the selected row
		if (GridView1.SelectedIndex > -1)
		{
		  if (GridView1.SelectedIndex == gr.RowIndex)
		  {
			// Loop through the columns for the selected row.
			foreach (DataControlField field in GridView1.Columns)
			{
			  if (field is System.Web.UI.WebControls.BoundField)
			  {
				if (((BoundField)field).DataField == strColumnName)
				{
				  columnIndex = GridView1.Columns.IndexOf(field);
				}
			  }
			}
			if (columnIndex > -1)
			{
			  // populate some variable with value contained in the ID column for the selected row
			  aVar = gr.Cells[columnIndex].Text; // I was getting NULL here

			  // raise a javascript alert displaying the ID we were looking for
			  // Define the name and type of the client scripts on the page. 
			  string csname1 = "PopupScript";
			  Type cstype = this.GetType();

			  // Get a ClientScriptManager reference from the Page class. 
			  ClientScriptManager cs = Page.ClientScript;

			  // Check to see if the startup script is already registered. 
			  if (!(cs.IsStartupScriptRegistered(cstype, csname1)))
			  {
				StringBuilder cstext1 = new StringBuilder();
				cstext1.Append("<script type=text/javascript> " + string.Format("alert('The ID column value for the selected row is: {0}');", aVar) + "</");
				cstext1.Append("script>");

				cs.RegisterStartupScript(cstype, csname1, cstext1.ToString());
			  }



			}

		  }

		}
	  }
	}

  }

Open in new window

0
 

Author Comment

by:Rad1
ID: 38339004
Excellent!!!!

Works great now!!!

Question:
Now it works as wanted, one problem I have is I am using
private static string theVar ;

Open in new window

as a global string holder
and
1) I need to Re-set it so it does not keep filling up every time the user clicks Button1.
2) I do not want it to be used by other pages.

What is the best way to do it?

Thank you all for your GREAT HELP and Support!!!!
0
 
LVL 26

Assisted Solution

by:Alan Warren
Alan Warren earned 1332 total points
ID: 38339040
Hi Rad1,

declare it private static, won't be available to other pages, but will be available to procedures within the same class. Then you can reset it to whatever from anywhere in the page_class

internal partial class yourpage_class : System.Web.UI.Page
{
  private static Int32 theVar;

Open in new window

Alan
0
 

Author Closing Comment

by:Rad1
ID: 38339128
Supper AAAAA

You guys are real Experts!!!!  And you should know it!

Also, it is good Alan that your are coding C# now :)  Always good to know more than you need!!!

Thank you informaniac and alanwarren for ALL your Great support!

Rad1
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
Integration Management Part 2

571 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question