Get cell value using row index and column index c# - 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

Related

DataGridView row header click giving last selected columns index

I am using CellClick event to get the row and column clicked.
Now when the row header is clicked, it gives me the last column selected index.
This will create an issue for me since i need to perform actions on the current selected row and column. How can i tackle this? I have seen tons of help but all of these talk about column header click.
Here is my basic test to check the row and col index when cell is clicked
private void dgvUsers_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (dgvUsers.CurrentRow == null || dgvUsers.IsLoading()) return;
var row = dgvUsers.CurrentCell.RowIndex; //CurrentRow.Index;
var col = dgvUsers.CurrentCell.ColumnIndex;
var ugactive = _ugActive;
}
In the above code, IsLoading is just an extension method that is checking for a particular text placed inside the tag.
In a DataGrdView CellClick() event, the current clicked cell can be determined inspecting the DataGridViewCellEventArgs e parameter, where e.RowIndex and e.ColumnIndex values report the reference indexes of the clicked cell Column and Row.
This also applies to Columns and Rows headers. In this case the value reported is negative (-1).
For example, if a Column header is clicked, e.ColumnIndex will report the index of the Column while the e.RowIndex will be -1. The opposite for a Row header.
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
//(...)
var row = e.RowIndex;
var col = e.ColumnIndex;
//(...)
}

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;
.
.

foreach looping only displaying last value of gridview

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;
}

first locating, then changing the value of a cell in a selected row in a datagridview?

Im trying figure out how I can change the value of a specific cell in a selected row of a datagridview. I am able to change the value but not in the highlighted row, only the first one. The hghlighting of the row is defined in the "find" button code.
For example: I enter a text, it search each row for that text in the specific column and then scrolls to and highlights/selects the entire row. (This Works Fine)
I then want to be able to get the value of a specific cell of the highlighted row by selecting the column name already present in the dropdownlist(combobox). It then gets the value of that cell and deducts from it a value present in a numericalUpDownCounter(nudQTY).
So far i can do this for different cells selected by column name (cbSupplList) but it only does it for the first row not the highlighted row defined by the "Find" button Code.
The following is my attempt so far:
private void btnFind_Click(object sender, EventArgs e)
{
/* Code to search the alphanumneric Part Number (in Column1 header called "PART NUMBER")
and highlihgt the row*/
foreach (DataGridViewRow row in dataGridView1.Rows)
{
// Removes the row selection
row.Selected = false;
var cellValue = row.Cells["PART NUMBER"].Value;
if (cellValue != null && cellValue.ToString() == tbPartNum.Text.ToUpper())
{
// Scrolls the found row up and highlights the entire row
row.Selected = true;
dataGridView1.FirstDisplayedScrollingRowIndex = row.Index;
}
}
}
private void btnSold_Click(object sender, EventArgs e)
{
int cellVal;
int newCellVal;
cellVal = Convert.ToInt32(dataGridView1.CurrentRow.Cells[cbSuppList.Text.ToString()].Value);
newCellVal = Convert.ToInt32(cellVal - nudQty.Value);
dataGridView1.CurrentRow.Cells[cbSuppList.Text.ToString()].Value = newCellVal;
}
It seems it may have to do with the SELECTED ROW in the "Find" code and the CURRENT ROW in the "Sold" Code. Making the SELECTED.ROW = CURRENT.ROW would solve it.... any ideas?
You are deselecting only Rows but no Cells.
dataGridView1.CurrentRow - "Gets the row containing current cell"
And Current Cell remains what it was = first cell of a first row.
In order to clear all selected rows/cells use
dataGridView1.ClearSelection()
And instead of
row.Selected = true;
use
row.Cells["PART NUMBER"].Selected = true;
As currently you are selecting only row but not the cell.
I hope this helps...
Otherwise you might want to find relevant cell in btnSold_Click() the same way you did in btnFind_Click()
.
.
EDIT
complete solution for you
private void btnSold_Click(object sender, EventArgs e)
{
int cellVal;
int newCellVal;
cellVal = Convert.ToInt32(dataGridView1.SelectedRows[0].Cells[cbSuppList.Text.ToString()].Value);
newCellVal = Convert.ToInt32(cellVal - nudQty.Value);
dataGridView1.SelectedRows[0].Cells[cbSuppList.Text.ToString()].Value = newCellVal;
}
I've just replaced CurrentRow with SelectedRows[0] and works fine.

Delete a Row from a DataGridView given its index

My DataGridView is a single line selection and theres a rowEnter Event where I get the line index every time the selected line changes.
private void rowEnter(object sender, DataGridViewCellEventArgs e)
{
currentRowIndex = e.RowIndex;
}
when I press a delete button I use the same index to delete the row
myDataSet.Avaliado.Rows[currentRowIndex].Delete();
avaliadoTableAdapter.Update(myDataSet.Avaliado);
it works fine if no column in the DataGridView is sorted, otherwise a get an error. What should be the way to know the row index in the dataset that corresponds to the rowindex from the DataGridView?
You don't need to be grabbing the current row index every time a new row is selected. Try something like this instead:
if (_Grid.SelectedRows.Count <= 0) { return; } // nothing selected
DataGridViewRow dgvRow = _Grid.SelectedRows[0];
// assuming you have a DataTable bound to the DataGridView:
DataRowView row = (DataRowView)dgvRow.DataBoundItem;
// now go about deleting the row however you would do that.
If you've got some other sort of data type bound to each row of the grid, simply cast the DataGridViewRow.DataBoundItem to whatever your data type is.
You can find the currently selected row at the time that you are doing the delete:
if(myDataGridView.SelectedRows.Count > 0)
currentRowIndex = myDataGridView.SelectedRows[0].Index;
I usually have the Primary Key for that row as a hidden column (my convention is using the first using column).
I can then ask my persistence Layer to do the rest.

Categories