20

I am using the GridView - AutoGenerateSelectButton = "True" to select the row in order to get the Column 1 cell value.

I have tried:

GridViewRow row = dgCustomer.SelectedRow;
TextBox1.Text = "Cell Value" + row.Cells[1].Text + "";

And it writes the "Cell Value" but nothing else.

I finally was able to get the number of the row (index) but not the cell value.

GridViewRow row = dgCustomer.SelectedRow;
TextBox1.Text = row.RowIndex.ToString();

I have tried:

TextBox1.Text = dgCustomer.Rows[row.RowIndex].Cells[1].Text;

and still returns the index row.

Any other suggestions? Thank you!

Matze
  • 5,100
  • 6
  • 46
  • 69
Lily
  • 221
  • 1
  • 2
  • 11
  • Trial and error. Try changing the index until you get the desired result. Cells[1], Cells[2], etc... – deostroll Aug 18 '14 at 18:05
  • I tried to Cells[6] and all give me the row index and not the value of the cell. Any other suggestions? Thank you! – Lily Aug 18 '14 at 18:09
  • Can you post some code here so we know what type of cell you are trying extract the value from? – deostroll Aug 18 '14 at 18:20

9 Answers9

27

Try changing your code to

// Get the currently selected row using the SelectedRow property.
GridViewRow row = dgCustomer.SelectedRow;

// And you respective cell's value
TextBox1.Text = row.Cells[1].Text

UPDATE: (based on my comment) If all what you are trying to get is the primary key value for the selected row then an alternate approach is to set

datakeynames="yourprimarykey"

for the gridview definition which can be accessed from the code behind like below.

TextBox1.Text = CustomersGridView.SelectedValue.ToString();
Dennis R
  • 3,195
  • 1
  • 19
  • 24
  • Do you really have value in `Cells[1]`? – Dennis R Aug 18 '14 at 19:25
  • I am assuming that I have a value since is column 1. – Lily Aug 18 '14 at 19:28
  • 1
    Not sure why all cell values are empty for you. Optionally you can set `datakeynames="yourprimarykey"` for the gridview and access the key value like `TextBox1.Text = CustomersGridView.SelectedValue.ToString()` – Dennis R Aug 18 '14 at 19:37
  • Dennis is working :) yeah I am soooooo excited please change the previous answer so I can give you the credit. OMG you have no idea how much stress you just took off my shoulders!!! – Lily Aug 18 '14 at 19:58
  • @Lily Glad it's working now. I've updated my answer with the alternate code. – Dennis R Aug 18 '14 at 21:21
8

Windows Form Iteration Technique

foreach (DataGridViewRow row in dataGridView1.Rows)
{
    if (row.Selected)
    {
        foreach (DataGridViewCell cell in row.Cells)
        {
            int index = cell.ColumnIndex;
            if (index == 0)
            {
                value = cell.Value.ToString();
                //do what you want with the value
            }
        }
    }
}
Nick Roberts
  • 245
  • 4
  • 12
4

I suggest you use a HiddenField inside template field use FindControl to find this field.

ie:

ASPX

                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:HiddenField ID="hfFname" runat="server" Value='<%# Eval("FileName") %>' />
                    </ItemTemplate>
                </asp:TemplateField>

Code behind

protected void gvAttachments_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        GridView gv1 = (GridView)sender;
        GridViewRow gvr1 = (GridViewRow)gv1.Rows[e.RowIndex];

        //get hidden field value and not directly from the GridviewRow, as that will be null or empty!
        HiddenField hf1 = (HiddenField)gvr1.FindControl("hfFname");
        if (hf1 != null)
        {
           ..
        }
    }
Fandango68
  • 4,461
  • 4
  • 39
  • 74
1

Have you tried Cell[0]? Remember indexes start at 0, not 1.

Fandango68
  • 4,461
  • 4
  • 39
  • 74
0

Expanding on Dennis R answer above ... This will get the value based on the Heading Text (so you don't need to know what column...especially if its dynamic changing).

Example setting a session variable on SelectedIndexChange.

    protected void gvCustomer_SelectedIndexChanged(object sender, EventArgs e)
    {
        int iCustomerID = Convert.ToInt32(Library.gvGetVal(gvCustomer, "CustomerID"));
        Session[SSS.CustomerID] = iCustomerID;
    }

public class Library
{
    public static string gvGetVal(GridView gvGrid, string sHeaderText)
    {
        string sRetVal = string.Empty;
        if (gvGrid.Rows.Count > 0)
        {
            if (gvGrid.SelectedRow != null)
            {
                GridViewRow row = gvGrid.SelectedRow;
                int iCol = gvGetColumn(gvGrid, sHeaderText);
                if (iCol > -1)
                    sRetVal = row.Cells[iCol].Text;
            }
        }
        return sRetVal;
    }

    private static int gvGetColumn(GridView gvGrid, string sHeaderText)
    {
        int iRetVal = -1;
        for (int i = 0; i < gvGrid.Columns.Count; i++)
        {
            if (gvGrid.Columns[i].HeaderText.ToLower().Trim() == sHeaderText.ToLower().Trim())
            {
                iRetVal = i;
            }
        }
        return iRetVal;
    }
}
Chris Catignani
  • 5,040
  • 16
  • 42
  • 49
0

I had the same problem as yours. I found that when i use the BoundField tag in GridView to show my data. The row.Cells[1].Text is working in:

GridViewRow row = dgCustomer.SelectedRow;
TextBox1.Text = "Cell Value" + row.Cells[1].Text + "";

But when i use TemplateField tag to show data like this:

 <asp:TemplateField HeaderText="料號">
    <ItemTemplate>
    <asp:Label ID="Part_No" runat="server" Text='<%# Eval("Part_No")%>' ></asp:Label>
    </ItemTemplate>
    <HeaderStyle CssClass="bhead" />
    <ItemStyle CssClass="bbody" />
    </asp:TemplateField>

The row.Cells[1].Text just return null. I got stuck in this problem for a long time. I figur out recently and i want to share with someone who have the same problem my solution. Please feel free to edit this post and/or correct me.

My Solution:

Label lbCod = GridView1.Rows["AnyValidIndex"].Cells["AnyValidIndex"].Controls["AnyValidIndex"] as Label;

I use Controls attribute to find the Label control which i use to show data, and you can find yours. When you find it and convert to the correct type object than you can extract text and so on. Ex:

string showText = lbCod.Text;

Reference: reference

劉鎮瑲
  • 517
  • 9
  • 20
0

I was looking for an integer value in named column, so I did the below:

int index = dgv_myDataGridView.CurrentCell.RowIndex;

int id = Convert.ToInt32(dgv_myDataGridView["ID", index].Value)

The good thing about this is that the column can be in any position in the grid view and you will still get the value.

Cheers

Mitchell Stone
  • 260
  • 2
  • 10
0

In SelectedIndexChanged event value from a selected row/cell can be found as below :

string id = gvLR.SelectedRow.Cells[3].Text.FromCellNumber();

In RowCommand event value from a hidden cell can be found as below:

HiddenField hdnProgramId = (((e.CommandSource as 
LinkButton).Parent.FindControl("SystemId")) as HiddenField);
string id = hdnProgramId.Value;

In SelectedRowDelete event value from any cell can be got as follow:

string _fileEntryId = gvLR.SelectedRow.Cells[1].Text;

For any/all row in the Gridview as follow:

foreach (GridViewRow row in gv.Rows) 
{
  if (row.RowType == DataControlRowType.DataRow)
   { 
   string _FileEntryId = ((HiddenField)row.FindControl("SystemId")).Value;
   string kk=row.Cells[3].Text; 
   } 
}
the-a-monir
  • 147
  • 1
  • 10
-2
string id;
foreach (GridViewRow rows in grd.Rows)
{
   TextBox lblStrucID = (TextBox)rows.FindControl("grdtext");
   id=lblStrucID.Text
}
UdayKiran Pulipati
  • 6,579
  • 7
  • 67
  • 92
Hafsal
  • 17
  • 2