foreach looping only displaying last value of gridview - c#

I'm binding my gridview with multiple datakeys. I'm trying to let these datakey value to be displayed on the textbox when a particular row of gridview is being selected. Therefore i tried the following method below.
I managed to store my database value into a string based on the column number. I'm using a foreach so as to loop the entire gridview when a particular row is being selected. But i'm not very sure why does it only display the last value of my gridview ?
protected void GWCase_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (GridViewRow gvr in GWCase.Rows)
{
string detail = GWCase.DataKeys[gvr.RowIndex].Values[0].ToString();
string propertydetail = GWCase.DataKeys[gvr.RowIndex].Values[1].ToString();
string suspectdetail = GWCase.DataKeys[gvr.RowIndex].Values[2].ToString();
tbdetails.Text = detail;
tbproperty.Text = propertydetail;
tbsuspect.Text = suspectdetail;
}
I cant really convert it into a proper for loop because i got the gridview row there as well. Basically, i'm trying to display out the different value of the different datakey based on the selected gridview row.

Well I think you want value from the selected row only. While looping you are not checking if the row is selected or not. That is why it shows only the stuff from last row. Try following:
protected void GWCase_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow selectedRow = GWCase.SelectedRow;
if(selectedRow == null) return;
/*GET VALUES FROM selectedRow AND DISPLAY THEM*/
}

Answer to your question: Basically, i'm trying to display out the different value of the different datakey based on the selected gridview row.
To get the values from the selected row, Use DataKeyNames property of GridView. Make sure you have a selectbutton present using AutoGenerateSelectButton="true" OR adding a button and set its CommandName Property to "Select".
Set DataKeyNames property to the Primary Key of your table. This can also contain more than one fields.
<asp:GridView ID="Employees" runat="server" DataSourceID="sourceEmployees"
DataKeyNames="EmployeeID">
In your selectedIndexChanged event, you can access the Value of this PrimaryKey column as well as other columns:
protected void gridEmployees_SelectedIndexChanged(object sender, EventArgs e)
{
int index = gridEmployees.SelectedIndex;
//retrieve the Primary Key field from the SelectedDataKey property.
int ID = (int)gridEmployees.SelectedDataKey.Values["EmployeeID"];
// Get other columns values
string firstName = gridEmployees.SelectedRow.Cells[2].Text;
string lastName = gridEmployees.SelectedRow.Cells[1].Text;
lblRegion.Text = gridEmployees.SelectedRow.Cells[9].Text;
}
One another way you can directly determine the data key value of the first key field of the selected row is by using the SelectedValue property
// Returns only the value of First DataKey Field
int ID = (int)gridEmployees.SelectedValue.ToString();

Managed to figure out the answer.
protected void GWCase_SelectedIndexChanged(object sender, EventArgs e)
{
int idx = GWCase.SelectedIndex; //add this line in
string detail = GWCase.DataKeys[idx].Values[0].ToString();
string propertydetail = GWCase.DataKeys[idx].Values[1].ToString();
string suspectdetail = GWCase.DataKeys[idx].Values[2].ToString();
tbdetails.Text = detail;
tbproperty.Text = propertydetail;
tbsuspect.Text = suspectdetail;
}

Related

In Gridview, I want to capture the Column Id's value for the selected Row

In Gridview, I want to capture the Column Id's value for the selected row. When I click "Select" and Click "Go" button, I receive this output:
Captured: MainContent_GridView1
How do I select the ID of that particular row?
protected void btnGo_Click(object sender, EventArgs e)
{
try
{
GridViewRow row = GridView1.SelectedRow;
String RowID = row.ClientID;
Response.Write("Captured: " + RowID);
}
catch (Exception ex)
{
Response.Write("Error:"+ ex.ToString());
}
}
One way to get the field values in a row is to add the field names to the DataKeyNames of the GridView:
<asp:GridView ID="GridView1" runat="server" DataKeyNames="Id,Phone" ... >
In code-behind, you can get the values this way:
int Id = (int)GridView1.DataKeys[row.RowIndex].Values["Id"];
string phone = (string)GridView1.DataKeys[row.RowIndex].Values["Phone"];
I included Phone in the list to show that several fields can be specified. In your case, DataKeyNames would only contain Id.
I think this is what you mean, you have a GridView that is showing the id in one of the columns. So, if it was the first column, you could do something like
GridViewRow row = GridView1.SelectedRow;
string id = row.Cells[0].Text;
Is that what you mean?
String Id = GridView1.SelectedRow.Cells[0].Text

C# Winforms DataTable cannot find the row with a specified id

I have a data table. I add a row to that data table. And i want to get the values of datagridview's selected row to some text box which data table is bound to. In my datagridview selection changed method i call find method of rows collection of datatable. But it gives me NullReferenceException.
private void dgvRecipeMaterial_SelectionChanged(object sender, EventArgs e)
{
if(dgvRecipeMaterial.SelectedRows.Count > 0 && isDgvRecipeMaterialReady)
{
int rowIndex = dgvRecipeMaterial.SelectedRows[0].Index;
int id = Convert.ToInt32(dgvRecipeMaterial.SelectedRows[0].Cells[0].Value);
object[] data = dtrecetemalzemejoin.Rows[0].ItemArray;
object[] items = dtrecetemalzemejoin.Rows.Find(id).ItemArray;
.
.
.
.
I looked to my id via debugger. Its value is 1166. And when i debug i see there is an item with the id 1166 from the data array. But find method cant find the id 1166. There is no problem if there is more then one record in the data table. What is the problem. data array has the id but find method cant find it.
DataTable.Rows.Find method searching for a rows by columns from DataTable.PrimaryKey property.
Check if your datatable primarykey contain column where your ID value is.
From MSDN: DataTable.PrimaryKey
If PrimaryKey columns did not set. Then before using Find method you set it like this:
dtrecetemalzemejoin.PrimaryKey = {dtrecetemalzemejoin.Columns[0]};
//or may be better will be using a name of column
dtrecetemalzemejoin.PrimaryKey = {dtrecetemalzemejoin.Columns["IDColumn"]};
can you try below code i was also getting same error
private void dgvRecipeMaterial_SelectionChanged(object sender, EventArgs e)
{
if(dgvRecipeMaterial.SelectedRows.Count > 0 && isDgvRecipeMaterialReady)
{
int rowIndex = dgvRecipeMaterial.SelectedRows[0].Index;
string id = Convert.ToString(dgvRecipeMaterial.SelectedRows[0].Cells[0].Value);
object[] data = dtrecetemalzemejoin.Rows[0].ItemArray;
object[] items = dtrecetemalzemejoin.Rows.Find(id).ItemArray;
.
.

Get cell value using row index and column index c#

I am trying to delete a user through his ID by selecting a cell/row in the DataGridview and then clicking on the delete button. I tried to get the ID by using the row index and column index. However, I am not able to delete the user as the value of 'string id' is NULL even when my datagridview contains rows.
private void buttonDeleteUser_Click(object sender, EventArgs e)
{
int rowindex = dataGridView1.CurrentCell.RowIndex;
int columnindex = 0;
string id = dataGridView1[rowindex, columnindex].Value.ToString();
controller_employee.delete_employee(Int32.Parse(id));
}
Why is it NULL and what can I do to resolve this?
ID = dataGridView.SelectedCells[0].RowIndex;
Here SelectedCells[0] specifies the column no.
And try selecting for whole rows rather than a single cell

Gridview , on row update get the value from a cell

I have a simple gridview.
3 Columns |
NAME AGE Birthday
On RowUpdated I want to get something like:
Gridview1.Column[2].Cell[2].Text
so I can get the value from the column 2. How can I do it?
Thank you.
pS: row updated & row updating are the same thing?
Here's the MSDN article with example code: GridView.RowUpdating Event
Row updated and updating are not the same. Updating happens before the GridView control updates the row and updated is after the data has been updated.
In your Gridview control you need to add OnRowUpdating="TaskGridView_RowUpdating"
Assuming the value is in a textbox in the Age column this is how you would store the value in a string:
protected void TaskGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = TaskGridView.Rows[e.RowIndex];
String str = ((TextBox)(row.Cells[1].Controls[0])).Text;
}
If you have data directly in the GridView cell (no label or textbox, etc) then this worked for me
protected void GridView1_RowUpdating(object sender,
System.Web.UI.WebControls.GridViewUpdateEventArgs e )
{
int row;
int colidx =1;
string cellvalue;
GridViewRow row = Gridview1.rows[e.rowindex]
cellvalue = row.cells[colidx].text;
}
Try this:
Gridview1.Rows[Gridview1.EditIndex].Cells[2].Text.ToString();

GridView1: How to save the selected value from the dropdownlist and make it visible

I have a dropdownlist.
A column called id has the control dropdownlist ( I've changed the
textbox into a dropdownlist).
The dropdownlist is containing 2 values : Yes/No .
On gridview row update I want to save the value choosed in the dropdownlist . how can I do that?
Also,how can I make the value choosed in the dropdown visible in the gridview.
thans
Try something like this
protected void GridViewRowUpdating(object sender, GridViewUpdateEventArgs e)
{
var rowIndex = e.RowIndex;
var row = GridView.Rows[rowIndex];
var ddl = row.FindControl("YOURDROPDOWN") as DropDownList;
if(ddl != null)
var value = ddl.SelectedValue;
}

Categories