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

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

Related

How to hide a DataGridVew row

In a C# WinForms project, I'm iterating through a DataGridView's DataSource as a DataTable and I'm doing a check on the source database and determining if a value in one of the columns is valid. If it is a valid value I want to hide it so I only end up with the DGV showing rows with invalid values.
Here's psuedo-code of what I have so far.
private void btnValidate_Click(object sender, EventArgs e)
{
DataTable dt = ((DataTable)dgvMyDataGridView.DataSource);
int intRowIndex;
for (intRowIndex = 0; intRowIndex <= dt.Rows.Count - 1; intRowIndex++)
{
DataRow drValidationRow = dt.Rows[intRowIndex];
string strNewValue = drValidationRow[5].ToString();
// Get the current row's db record ID as a string for the db query
int intCurrDgvRowId = int.Parse(dgvMyDataGridView[0, intRowIndex].Value.ToString());
// Determine if we need to show or hide the DGV's row
bool bNewValueIsValid = <db check for valid strNewValue>
if (bNewValueIsValid)
{
/*
* Hide the DGV row corresponding to the DT row ID
*/
}
}
}
I tried what seems most logical to me:
dgvmyDataGridView.Rows[intRowIndex].Visible = false;
But when I run that I get this error:
System.InvalidOperationException: 'Row associated with the currency manager's position cannot be made invisible.'
I can't just do something like drValidationRow.Visible = false, as there's no Visible property on that, I'm guessing because the row is from the DataTable not the DGV.
How do I accomplish this?
you dont need a counter. You can just refresh dgv if Rows.Count = 0 ?

Filter expression does not evaluate to a Boolean term, C#

I have a comboBox that is populated with the headers of a database.
When a user selects an header, i want to display the values of that column in a listBox.
I am trying to do it this way.
private void button3_Click_2(object sender, EventArgs e)
{
listBox1.Items.Clear();
//name of column to display data from
var selectedColumn = comboBox1.Text.ToString();
//dataRow array of data
var selectedColumnItems = aSH_ORDER_DBDataSet1.ASH_PROD_ORDERS.Select(selectedColumn);
//iterate through dataRow and display in listBox
foreach (var columnItem in selectedColumnItems)
{
listBox1.Items.Add(columnItem);
}
}
However, if i select a non boolean type column it get this error:
"Filter expression does not evaluate to a Boolean term"
And even when i do select a boolean column, it just displays the name of the program. It does however seem to be getting some data from the database as it displays the correct number of program names from the number of "true" terms in the database.
If you want to show the content of a single column without any condition you don't need to SELECT but you just loop over the rows of your table
private void button3_Click_2(object sender, EventArgs e)
{
listBox1.Items.Clear();
//name of column to display data from
var selectedColumn = comboBox1.Text.ToString();
//iterate through dataRow and display in listBox
foreach (DataRow row in aSH_ORDER_DBDataSet1.ASH_PROD_ORDERS.Rows)
{
listBox1.Items.Add(row[selectedColumn].ToString());
}
}
The DataTable.Select method is used when you need to filter the content of the table adding some kind of expression that could be parsed to a boolean value.
DataRow[] result aSH_ORDER_DBDataSet1.ASH_PROD_ORDERS.Select("ColumnName = 'ColumnValue'");
In the example above we take a subset of the table rows that have the 'ColumnValue' string present in the column named 'ColumnName'.
Other useful uses of Select are tied to the creation of a new Table with a particular order. See the DataColumn.Select and the DataTableExtensions.CopyToDataTable documentation

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

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

How to get Column Value of a DataRow in a Datatable

I have a DataTable which is bind to dataGridview in my code.
When I get datas from database, the gridview works fine. it fills with data.
What I want to do is getting the primary key value of the specified row.
Ex:
PK Address Phone
1 xxxyyyzzz... 1234567
2 aaabbbccc... 2345678
What I want is this. User will click on any row, then click on a button to add some stuff.
Then I will get PK value, and do other stuffs.
How can I do it?
Hmm can you specify how and when you are talking about getting this value?
You can do this:
int index = dt.Rows.IndexOf(row);
But I am not sure what the point of that would be, if you already have the specified row, why can't you just get the PK via row[columnName]?
But this is more resource intensive than just looping through with a for loop.
Do you need this before or after binding to the dataGridView? If you need to get the value from the dataGridView row that is different.
For your edit:
You would can get the selected row like so:
if (yourDataViewGrid.SelectedRows.Count == 1)
{
Int pk = yourDataViewGrid.Rows[yourDataViewGrid.SelectedRows[0].Index].Cells["PK"].Value.ToString();
}
If you are doing it by some other method like using a checkbox to select a row, you would do this:
foreach (DataGridViewRow row in YourDataGridView.Rows)
{
if ((Boolean)((DataGridViewCheckBoxCell)row.Cells["CheckBoxName"]).FormattedValue)
{
Int pk = rows.Cells["PK"].Value.ToString();
}
}
The DataGridView control binds to a DataTable using the DataView class. You can use something like this to get the DataRow of a DataGridViewRow
var vrow = (DataRowView)grid.Rows[12].DataBoundItem; // get the bound object
var drow = vrow.Row; // the Row property references the real DataRow
where 12 is the index you are looking for. Sometimes it helps to set the DataSource property to a DataView explicitly and keep a reference to it on your form. The view will know the sorting of the data too
var view = new DataView(table);
grid.DataSource = view;

Categories