Accessing properties of SelectedRow during SelectedIndexChanged event in dynamically generated GridView - c#

I have an empty GridView object on a page that I bind to a LINQ qry result at run time. The GridView has a 'Select" button that fires the SelectedIndexChanged event and it's inside of this event that I'd like to access the data of one of the fields in the selected row.
So far, I can only find one way to do this, and it seems suboptimal:
protected void GridView2_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView2.SelectedRow;
string UserID = row.Cells[1].Text;
//Do stuff with the userID
}
So this just access the cell data directly based on the cell index. The UserID just happens to be in the second cell and so it works. But later down the road, the UserID may not be in that same column. It seems like I'd be better off looking up the value of this cell by accessing by the cell's header name, or by any method other than the cell index itself.
Any ideas?
Thanks!

Try this
User user = (User)((DataRowView)row.DataBoundItem).Row;
int userID = user.UserID;
I am assuming you have a class called User and you are binding the DataGridView to may a List

I don't know much about asp.net, but in the C# DataGridView you can index columns directly by column name, i.e.
string UserID = row.Cells["UserID"].Text;
or something like that. Might be worth a try.

You can use following code to retrieve object bound to current SelectedRow.
DataTable dt = (DataTable)<GridViewControl>.SelectedRow.DataItem
(here I have assumed that Grid is bound with DataTable.)

Related

How to set and get the value of Data Bind Gridview Combobox Column in C#

I have a data grid view with combo box column in it, i have bind that column to datatable like this:
((grdItems.Columns[1]) as DataGridViewComboBoxColumn).DataSource = dt;
((grdItems.Columns[1]) as DataGridViewComboBoxColumn).DisplayMember = "LocationName";
((grdItems.Columns[1]) as DataGridViewComboBoxColumn).ValueMember = "Id";
now i can get the selected value like this:
var value = grdItems.Rows[0][1].Value;
but the issue is, when i manually add the rows in the gridview (without binding the grid), i cant get the value of the combobox cell.
i am adding rows like this:
grdItems.Rows.Add(1, 1, "Some Value");
when i use
var value = grdItems.Rows[0][1].Value;
this method to get the value, i returns me the text of the cell not the value i.e 1 in this case.
How can i solve this issue? since i want the value of the cell in case of adding rows manually, as well as data-bind rows.
Am assuming that by manually adding rows you mean from the UI , so one way to get the value of the newly added row is to use an event handler for the events raised when you add an row. You may use one of the following
1) RowsAdded https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.rowsadded(v=vs.110).aspx 2) RowPrePaint - https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.rowprepaint(v=vs.110).aspx - not used this much but is also an option
this.myGridView.RowsAdded += new DataGridViewRowsAddedEventHandler(myGridView_RowsAdded);
private void myGridView_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
var newRow = this.myGridView.Rows[e.RowIndex];
}
Edit: Based on the actual requirement stated in the comments - actual requirement being retrieving the newly added row's cell value (Id) corresponding to the combox box column on button save clicked event
Assuming you have bound the combo box to a data source itself , meaning, your
combobox.DataSource=someList
so what you can do is write a linq query
someList.Where( v=>v.Text.Equals("row.Cells[1].Value")).FirstOrDefault().Id

Pass one row from grid view to another grid view asp.net c#

I am wondering of how to pass data, that's one row from Grid View1 to Grid View2 in the same Web form!I created two tables, the first one contains four columns and contains records: Id, name, address and age.
I also created the second form which also contains four columns: Id, name, address and age, but left empty for purpose of transmitting data from the first table.
I wonder if it is possible if to select one row from Grid view1 and then click a button which enables to pass that selected row to Grid View2 !? One row each a time added after hitting the send button to the second grid view and guarantees that data added to the second table!
Any ideas of how to do that would be much appreciated.
I'll give you an overview of some steps you might want to take
I assume you use a DataSet or a DataTable where your records are stored in.
use the eventHandler of the gridview, like CellClick, most of them have a e.RowIndex value, which you can use to get the index of the row that is selected
Like this:
private void dg1_CellClick(object sender, DataGridViewCellEventArgs e)
{
selectedIndex = e.RowIndex;
}
use that index to get the id from that record, so you know what data you are talking about
like this:
int id = Convert.ToInt32(dataset1.Tables[0].Rows[selectedIndex][0]);
then just find the row by id or use the knowledge above to combine this
DataRow row = dataset1.Tables[0].Rows.Find(Id);
dg2.Rows.Add(row);
it's better to use datasets and give the datagridview a datasource to that dataset, not sure what your intentions are
you could also get the id from the row you selected, based on that you call another sqlCommand to get that current row, a good way if you have more data you want to load from the database that rely on that id

Number of Rows in Gridview datasource

I need to find and display the number of rows returned by the query. This query is made using an SQLDataSource object, which is bound to an asp.net GridView control. How can I find this information?
You can't use the Rows property on the grid, because that only gives you what the GridView is currently rendering. You need to hook up to the Selected event on the SqlDataSource and then you can pull the AffectedRows property.
protected void SqlDataSource1_Selected(object sender, SqlDataSourceStatusEventArgs e) {
int totalRows = e.AffectedRows;
}
I would suggest that you handle the SQLDataSource.Selected event and check the e.AffectedRows property. It returns the number of selected rows. Also, it is possible to obtain this information programmatically:
DataView dv = (DataView)SQLDataSource1.Select(DataSourceSelectArguments.Empty);
int rowCount = dv.Count;
NOTE: this code will result in selecting data once again. So, the best solution is to use the Selected event for this purpose.

Gridview making a column invisable

Hi I have a grid view which is dynamically generated via C# using a DataSet.
I'm passing a row ID field (from the database) to the grid view, as this is required when a user clicks to edit a records. However I don't want the user to be able to view the column.
I have tried the following but it doesn’t seem to work? Could anyone suggest a way to hide the column or a better way of attaching the information to the grid view row so it can be used at a later stage.
c#
DataColumn ColImplantCustomerDetailsID = new DataColumn();
ColImplantCustomerDetailsID.ColumnName = "Implant ID";
ColImplantCustomerDetailsID.DataType = typeof(int);
ColImplantCustomerDetailsID.Visable = false; <-- visable doens't work here.
asp.net
DataColumn doesn't have a 'Visable' property. Heck, it doesn't have a 'Visible' property either.
Use this before you bind
gridviewNameHere.Columns[index].Visible = false;
You can make it visible again on one of your event handlers.
Another option, rather than hiding the column, is to use the DataKeyNames property of the GridView to store the name of the ID field. You can then use myGridView.SelectedValue to retrieve the selected ID.
Use the index of the column to hide it when you initialize it...
grid.Columns[index].Visible = false;
I actually hide a few things as you are suggesting, example - database status names for that row that can be used in code that the user does not need to see.
Accessing GridView Invisible Columns
http://www.highoncoding.com/Articles/178_Access_GridView_Invisible_Columns.aspx
In the OnRowDataBound event of the GridView component:
// c#
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
int index = 0; // put the index of the column you need hide.
e.Row.Cells[index].Visible = false;
}

asp.net finding column from dynamic gridview

I'm creating a dynamic GridView from a DataTable that is returned from a stored procedure. I call and bind with the following code:
DataTable dt = Sql.reportData(Convert.ToInt32(Session["userID"]));
this.GridView1.DataSource = dt.DefaultView;
this.GridView1.DataBind();
I need to restyle certain columns but they are not always the same column number, and only have the headers text string to identify it. Is there an easy way to track a column down like this so I can edit its attributes?
Thanks,
Alex
I've run into this myself. You've got to loop through the column names, get the index, and then refer to the index to manipulate the style.
Muhammad is right about the timing, but you won't be searching for a label--it seems you want to style the entire column, right?
http://forums.asp.net/p/1076872/1584635.aspx
the above has several versions of a solution.
The best place to find the control and use it will be in the RowCreated event. RowDataBound should not be used because you dont have to manipulate the data with which the column is being binded. So restyle the elements in the column by searching them in the RowCreated event.
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
e.Row.FindControl("");
}

Categories

Resources