Get value from GridView - c#

I am trying to get the value from a GridView and save it as a Session variable.
I know the column name and there is only ever one value in the GridView. What is the best way to select it and save as the Session variable?
The column name is CustomerID and the value is always a int.

if there is one column and one row in the GridView you can try below.
Session["MySessionValue"]= GridView1.Rows[0].Cells[0].Text;
but exception can be thrown when you access by index if there is no records in the GridView. So better to check GridView1.Rows.Count First and get the value

This is not a proper way to do this, you better hardcode the cellindex but anyways a little longer version of Damith's answer
if (GridView1.Rows.Count > 0)
{
int indexofcolumn = 0;
foreach (DataControlField column in GridView1.Columns)
{
if (column.HeaderText == "CustomerID") break;
indexofcolumn++;
}
Session["CustomerID"] = GridView1.Rows[0].Cells[indexofcolumn].Text;
}

You can set a DataKey for GridView as CustomerID and select by:
int ID = Convert.ToInt32(GridView1.DataKeys[indx].Value);
indx is Row Index in GridView..

Related

Displaying original rowindex after filter in datagridview

Just want to ask on how to get the original row index of selected row in DataGridView after filter.
I have DataGridView with 2 columns :name and age. And I have a TextBox that serves as filter. Let's say I have 8 records and upon filtering it goes to only 4 records and upon clicking the last record, I get row index of 4, while I need to get the original index of this row and display it on MessageBox. How will I do it?
Thank you.
Original row index means the index of the DataRow in the DataTable which can be found by DataTable.Rows.IndexOf(row). So to find the original index of the row you can use the following code:
var r = ((DataRowView)BindingContext[dataGridView1.DataSource].Current).Row;
var index = r.Table.Rows.IndexOf(r);
In case you are interested to do that for all rows in the DataGridView, as also is mentioned by Taw in comments, you can look into the DataBoundItem of the DataGridViewRow:
var r = ((DataRowView)dgvRow.DataBoundItem).Row; // dgvRow is a row of the DataGridView
var index = r.Table.Rows.IndexOf(r);
From your comments you said that you need it to display current record selected so I will not directly answer How to get row index on filtered table but how to get current record selected.
So to simply get current selected record use this code:
//Use this one if your datagridview SelectionMode is not FullRowSelect
DataGridViewRow row = dataGridView1.Rows[dataGridView1.SelectedCells[0].RowIndex];
string name = row.Cells["Name"].Value.ToString();
int age = Convert.ToInt32(row.Cells["Age"].Value);
//If your datagridview SelectionMode is FullRowSelect then use this
DataGridViewRow row = dataGridView1.SelectedRows[0];
string name = row.Cells["Name"].Value.ToString();
int age = Convert.ToInt32(row.Cells["Age"].Value);
Reza answered main part of your question but if for some reason it is not working you can use this since your primary key is your NAME
foreach(DataRow r in yourDataTable.Rows)
{
if(r["NAME"].ToString() == row.Cells["Name"].Value.ToString()) //This row.cells... is the one from above code
{
int originalRowIndexInDataTable = dt.Rows.IndexOf(r);
return;
}
}

How to get the first column value of a selected row in GridView

I have a GridView
How do I get a value of a column for a given row.
I tried the following but it only gives the row number instead of the value:
int selRowIndex = ((GridViewRow)(((System.Web.UI.WebControls.CheckBox)sender).Parent.Parent)).RowIndex;
you are looking for the contentnot the index
var cellText= ((GridViewRow)(((System.Web.UI.WebControls.CheckBox)sender).Parent.Parent)).Cells[0].Text;
and then convert it to int

getting index of a column having a given column header c#

guys i am trying to get the index of a column with a specific column header.
Till now i got to
int index_of = grid_statement.Columns[the_name].Index;
But it throws a NullReference exception.
Is there any other ways to get that index ?
(the_name is a variable having the column header)
If your are trying to get column by it's name, then either your grid is null, or there is no column with name equal to the_name in your grid. In both cases you will not be able to get index of non-existing column. To avoid exception in case there is no column with provided name, you can check if column exists before trying to get its index.
var column = grid_statement.Columns[the_name];
int index_of = column == null ? -1 : column.Index;
If you are trying to get column by it's header text (which is not same as column name) you should search for column with same header. And if column was found, get it's index:
var column = grid_statement.Columns
.Cast<DataGridViewColumn>()
.FirstOrDefault(c => c.HeaderText == the_name);
int index_of = column == null ? -1 : column.Index;
try this it will helps you
int index_of = grid_statement.CurrentRow.Cells["ColumnName"].ColumnIndex;
You are probably trying to access the columns collection before binding the data source. At this time gridview wont have any columns. Assign dataSource and bind the grid and then check the index of column.
grid_statement.DataSource = dataTable;
grid_statement.DataBind();
int index_of = grid_statement.Columns[the_name].Index;
To avoid exception you should first check if you got column then get its index.
int index_of = -1;
if(grid_statement.Columns[the_name] != null)
index_of = grid_statement.Columns[the_name].Index;

How to select row in Telerik RadGrid?

When user select a row in Telerik Rad Grid, i want to take fields in this row. how to do this?
It's a little tricky, but easy after you've done it once.
Step 1.
Go to the Radgrid itself and edit the field DataKeyNames="" (under MasterTableView) and add the datafield you are pulling:
<MasterTableView ... DataKeyNames="ColumnNameFromSqlGoesHere">
Step 2.
Decide how you are going to grab the values, on Row Change (SelectedIndexChanged) or on a buttong press with a command attached to it (ItemCommand).
If row change, per your question:
protected void RadGrid1_SelectedIndexChanged(object sender, EventArgs e)
{
var z = RadGrid1.SelectedItems[0].OwnerTableView.DataKeyValues[RadGrid1.SelectedItems[0].ItemIndex]["ColumnNameFromSqlGoesHere"];
}
This will assign the variable "z" to the value of the column you have chosen (ColumnNameFromSqlGoesHere) at that given row.
If you wish to select multiple variables every time you change row you need to add all the values you wish to select under the DataKeyNames=" ". (Seperated by commas). You would then fetch each value via the code seen in the SelectedIndexChanged method:
var a = RadGrid1.SelectedItems[0].OwnerTableView.DataKeyValues[RadGrid1.SelectedItems[0].ItemIndex]["SecondColumnGoesHere"];
var b = RadGrid1.SelectedItems[0].OwnerTableView.DataKeyValues[RadGrid1.SelectedItems[0].ItemIndex]["ThirdColumnGoesHere"];
Etc... You get the idea.
This should get you going. It is a solution straight from Telerik: Retrieving primary key values for selected items
Try this. This may help you.
STEP 1:Add one radiobutton column in the radgrid
STEP 1: Get the primary key of selected row in the radgrid.
int primaryKey =0;
RadioButton radioButton;
for (int i = 0; i < RadGrid1.Items.Count; i++)
{
radioButton = RadGrid1.Items[i].FindControl("rdSelect") as RadioButton;
If (radioButton.Checked)
{
primaryKey = RadGrid1.MasterTableView.Items[e.Item.ItemIndex]["ID"].Text;
}
}
Line in the if condition will be used to get the fields from the selected row just by changing the fields datakey name i.e. changing "ID" to other field
Read this article for more details...
http://codedotnets.blogspot.in/2012/01/get-primary-key-selected-radiobutton.html

Get Column Header in TableCellCollection in asp.net

I am using a website and i have a gridview in that website.... I want to delete a row in that gridview by using that selected row column values and Column headers... i got the column values by using TablecellCollection but i cant get that column value's Corresponding Column header.... how shall i get that Column header by using TableCellCollection....
Please anyOne Tell me the solution of this....
Thanks in Advance!
And My code is:
int Row = Convert.ToInt16(e.RowIndex);
TableCellCollection collection = GrdViewDetails.Rows[Row].Cells;
for (int i = 0; i < Collection.Cells.Count;i++)
{
strColumnValue = Collection.Cells[i].Text;
//strColumnName=?
}
GrdViewDetails.Columns[i].HeaderText

Categories

Resources