I am in need of a simple way for checking if my datagridview is/isn't empty.
The Rows.Count does not satisfy me, because my program starts with 2 empty rows,
and in the future the datagridview could be populated and then the count
does not affect anything
(If the users deletes a section but there are more than 2 rows present).
Is there anyway of checking this?
well these are the checking options for whether datagrid view is empty or not ......
if(DataGridView1.Rows.Count == 0)
{
MessageBox.Show("DataGridView is empty");
}
2). You can check the DataTable or DataSet which binds to
DataGridView:
if(dt == null)
{
MessageBox.Show("DataGridView is empty");
}
if(ds == null)
{
MessageBox.Show("DataGridView is empty");
}
you can check with datagrid view cell value also by using this:
if (dataGridView1.Columns[e.ColumnIndex].Name == "companyName")
{
if (String.IsNullOrEmpty(e.FormattedValue.ToString()))
{
dataGridView1.Rows[e.RowIndex].ErrorText =
"company Name must not be empty";
e.Cancel = true;
}
}
dataGridView1 with enable Adding:
using System.Linq;
if (dataGridView1.Rows.OfType<DataGridViewRow>().Take(2).Count() > 1)
{
MessageBox.Show("dataGridView1 has at least 2 rows");
}
dataGridView1 with disable Adding:
if (dataGridView1.Rows.OfType<DataGridViewRow>().Any())
{
MessageBox.Show("dataGridView1 has row");
}
Related
I have a List<Car> objects that have a bool property named Marked.
I want to check / uncheck the Cell corresponding to this property, in a way that only one Car can be selected at the same time.
I want that the value of this property is updated in the bank.
Sample table:
Car Name
Marked
a
b
The problem is I can't check the state of CheckBox Cells.
This is what I tried, but it's not working:
Example 1:
DataGridViewCheckBoxCell dataGridViewCheckBoxCell = DataGridView1.Rows[e.RowIndex].Cells["Marked"] as DataGridViewCheckBoxCell;
if(Convert.ToBoolean(dataGridViewCheckBoxCell.Value) == true)
{
//some code
}
else if(Convert.ToBoolean(dataGridViewCheckBoxCell.Value) == false)
{
//some code
}
Example 2:
foreach (DataGridViewRow row in DataGridView1.Rows)
{
DataGridViewCheckBoxCell chk =(DataGridViewCheckBoxCell)row.Cells["Marked"];
if (chk.Value == chk.TrueValue)
{
chk.Value = chk.FalseValue;
}
else
{
chk.Value = chk.TrueValue;
}
}
how can I do it?
You can handle the CellContentClick (or CellClick) event of your DataGridView to set the state of a DataGridViewCheckBoxCell that should be a single choice (hence behaving as a RadioButton).
Store the Cell object currently selected when the Cell meets the criteria (its OwningColumn is a DataGridViewCheckBoxColumn named Marked).
Change the state of this Cell if it's the one currently selected, or reset it back to false if it's not.
In this case, set the current Cell to the one just selected and set its state to true.
Then you don't need to loop all the Rows each time a CheckBox changes value.
If you need to, call [DataGridView].EndEdit() to update the value immediately.
For example:
DataGridViewCheckBoxCell currentCheckBoxCell = null;
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex < 0 || e.RowIndex < 0) return;
var dgv = sender as DataGridView;
if (dgv[e.ColumnIndex, e.RowIndex] is DataGridViewCheckBoxCell cell &&
cell.OwningColumn.Name == "Marked")
{
if (currentCheckBoxCell is null) currentCheckBoxCell = cell;
if (cell == currentCheckBoxCell) {
cell.Value = !(bool)cell.Value;
}
else {
currentCheckBoxCell.Value = false;
currentCheckBoxCell = cell;
}
// Affects CellValueChanged
// dgv.EndEdit();
}
}
This is how it works:
See also DataGridView CheckBox selection bug to select a CheckBox Cell by clicking anywhere in a Row and while immediately update the data source.
It is unclear “where” the first code snippet is called from so I will focus on the second snippet of code.
One of the problems you will have comes from the if statement…
if (chk.Value == chk.TrueValue) …
This condition chk.Value == chk.TrueValue may not throw an error, HOWEVER… this is checking two different OBJECTS… chk.Value is an OBJECT as is chk.TrueValue … so it makes sense that the two “different” OBJECTS would NEVER be equal.
One way to solve this is to simply “cast” those OBJECTS to bool values like…
if ((bool)chk.Value == (bool)chk.TrueValue) {…
HOWEVER the above line of code will ONLY work “IF”… the check box columns TrueValue AND FalseValue properties have been SET like…
CheckBoxColumn.TrueValue = true;
CheckBoxColumn.FalseValue = false;
IF you have NOT set the Check box column’s two properties TrueValue AND FalseValue like above… then the Check box columns TrueValue and FalseValue will be null and this will cause the line of code … if ((bool)chk.Value == (bool)chk.TrueValue) … to throw an exception since chk.TrueValue is null and the cast to a bool will throw a null exception.
Therefore, if you DO SET the Check box columns TrueValue and FalseValue then you will have to “cast” the objects to bool values in order for the comparison to work as shown above.
Given all this… you may want to re-consider using the Check box columns TrueValue and FalseValue as the intended purpose of those properties is to allow you to “change” the actual true and false values to something else that is not necessarily a true or false value.
It is unimportant how you would use these properties in that context as it appears very clear that in this context… setting the Check box columns TrueValue and FalseValue properties to true and false is somewhat superfluous and creates more work for you.
So in this case, I suggest you completely drop using the Check box columns TrueValue and FalseValue properties.
If you want to ensure that only ONE check box is checked in the column… then you could wire up the grids CellContentClick event. If the check box value changed, then simply “uncheck” all the cells in that column.
Fortunately, the grids CellContentClick will fire “before” it actually sets the check box cell, so unchecking them all works out fine for both checked and unchecked states. Crude yes, but it should work.
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) {
if (dataGridView1.Columns[e.ColumnIndex].Name == "Marked") {
foreach (DataGridViewRow row in dataGridView1.Rows) {
if (!row.IsNewRow) {
row.Cells["Marked"].Value = false;
}
}
}
}
I hope this makes sense and helps.
I have a DataGridView where the values found in the 1st column should not be repeated, and neither should it have any blank columns. This is the method I've implemented in order to remove this repetition:
public static void eliminateRepetition(DataGridView table)
{
for (int currentRow = 0; currentRow < table.RowCount; currentRow++)
{
DataGridViewRow rowToCompare = table.Rows[currentRow];
foreach (DataGridViewRow row in table.Rows)
{
if (row.Equals(rowToCompare)) // If the row to compare is the current row, skip
{
continue;
}
if (row.Cells[0].Value != null && rowToCompare.Cells[0].Value != null)
{
if (int.Parse(row.Cells[0].Value.ToString()) != int.Parse(rowToCompare.Cells[0].Value.ToString())) // 1st column values must match in order to be considered as a repetition
{
continue;
}
else
{
table.Rows.Remove(row); // Remove repeated row
}
}
else
{
table.Rows.Remove(row); // Remove blank rows
}
}
}
}
The result I have is always 2 rows with the same value in the 1st column.
Any help will be much appreciated.
After removing a row from the table, the indexes change. Next iteration will not be as expected.
I think it would be better to create a list of objects. Make them unique in terms of your rule. Then set the DataSource property of the datagridview to the object list you have.
I'm populating datagrid view like this.
var dataTable = new viewregisterdVotersOP().getTableRegVoters(lgdiv, elecid);
if (dataTable == null || dataTable.Rows.Count == 0)
{
tempmsg1 = "Couldn't find data in the system";
setErrorMSG(tempmsg1);
}
else
{
dgvView.DataSource = new viewregisterdVotersOP().getTableRegVoters(lgdiv, elecid);
}
But it adds an extra empty row. How to stop that?
But it adds an extra empty row. How to stop that?
That row is there to allow users to add new rows to grid, you can disable that either in code behind or at design view using DataGridView.AllowUserToAddRowsproperty
In code behind:
dgvView.AllowUserToAddRows = false;
Or set the property to false in design view.
I have a datagridview in a WinForms application and I want all columns bar one to be locked to editing. This I was able to achieve with the following code:
foreach (DataGridViewColumn col in myGrid.Columns)
{
if (col.Name == "LockedColumn")
{
col.ReadOnly = false;
}
else
{
col.ReadOnly = true;
}
}
However, I also need a conditional lock on this column, dependent on the values elsewhere in each row. I tried the following code:
foreach (DataGridViewRow row in myGrid.Rows)
{
if ((bool)row.Cells["ConditionalColumn"].Value == false)
{
row.ReadOnly = false;
}
else
{
row.ReadOnly = true;
}
}
However this locks the whole grid which is not what I want. What I'm after may be clearer with a table example.
ColA ColB ColC
row1 true value1
row2 false value2
row3 true value3
I want Columns A & B locked (read only) in their entirety, and the default for Col C to allow editing, except where the value in Column B is false. Hence in the above example only value1 and value3 would be editable.
However I can't seem to achieve this, because as stated above, if I loop through the rows with a condition that sets readonly to false, everything is locked.
The code you have shown should not compile and also isn't correctly examining the values within boolean cells in a DataGridView.
If you change your code to look at rows to something like the code below then you should be able to set individual rows to read only based on the column:
foreach (DataGridViewRow row in myGrid.Rows)
{
if (row.Cells["ConditionalColumn"].Value == null || (bool)row.Cells["ConditionalColumn"].Value == false)
{
row.ReadOnly = false;
}
else
{
row.ReadOnly = true;
}
}
It was the following line that was the issue
row.ReadOnly = false;
When changed to
row.Cells["colName"].ReadOnly = false;
it works as intended
I already tried this way but it is not working.
How do I fix it?
if(dgvProducts.Rows.Count < 1 )
{
MessageBox.Show("Something");
return;
}
you may try something like this,
if(dgvProducts.Rows.Count > 1 )
{
MessageBox.Show("Something");
return;
}
if it doesn't works then you may also try something like this too,
string nrCode = dataGridView1.Rows[0].Cells[6].Value.ToString();
nrCode = nrCode.Trim();
if (nrCode == string.Empty)
{
MessageBox.Show("there must be Entry in cell nrCode on first row.")
}
the above code will allow you to check if specific cell in first row in DataGridView is empty.
Hope it works.