CellClick Event not working on some rows in Data Grid View - c#

As stated in the title, I have noticed some weird behaviour with my Data Grid View control. The cell click event is supposed to load details from the rows into textboxes and datepicker controls. This works for some rows of the data grid view but other rows are outright ignored.
The code:
`
private void dataGridViewAdmin_CellClick(object sender, DataGridViewCellEventArgs e)//Textbox and datepicker field input automation
{
if (e.RowIndex == -1)
{
return;
}
//Automatically fills the text fields with the User's selection.
DataGridViewRow selectedRow = dataGridViewAdmin.Rows[e.RowIndex];
txtName_Field.Text = selectedRow.Cells[1].Value.ToString();
txtPhone_Field.Text = selectedRow.Cells[5].Value.ToString();
try
{
dataGridViewAdmin.Rows[e.RowIndex].Selected = true;
datepickerEnd.MaxDate = (Convert.ToDateTime(selectedRow.Cells[4].Value)).AddDays(+7);
datepickerEnd.MinDate = (Convert.ToDateTime(selectedRow.Cells[3].Value)).AddDays(+1);
datepickerStart.Value = Convert.ToDateTime(selectedRow.Cells[3].Value);
datepickerEnd.Value = Convert.ToDateTime(selectedRow.Cells[4].Value);
Booking_ID = Convert.ToInt32(selectedRow.Cells[7].Value);
lblID.Text = "Selected ID: " + Booking_ID;
lblID.Visible = true;
}
catch (ArgumentOutOfRangeException) //Catches exception thrown if user from rows of data that have values that are more than seven days apart.
{
if(datepickerEnd.MaxDate < datepickerEnd.MinDate)
{
datepickerEnd.MaxDate = datepickerEnd.MinDate.AddDays(+7);
}
}
`
I've set a breakpoint within the code to see if it breaks on cell click. It breaks for some cells and does nothing on others. Naturally, I've tried spamming the mouse in on the problem cells to no effect.
I've tried to sort the rows differently, still no change.
Your help with this question will be appreciated.

Related

Combobox Selected Value going "null" on GridView_CellClick Event

I am using Winforms with C# and I am getting this result.
I have a gridview where some data are loaded and in cell click event, the data is displayed on text boxes and combobox, however, one of the combobox has gone crazy and not displaying the data on select. When debugging the code, the SelectedValue goes to null while on other combo boxes, the value changes.
Below are the codes used.
Gridview cell click event
if (e.RowIndex != -1)
{
DataGridViewRow grid = stockGridView.Rows[e.RowIndex];
txtStockId.Text = grid.Cells[0].Value.ToString();
txtBarcode.Text = grid.Cells[1].Value.ToString();
cmbQtyDescId.SelectedValue = grid.Cells[2].Value;
txtQtyDesc.Text = grid.Cells[3].Value.ToString();
txtBrandName.Text = grid.Cells[4].Value.ToString();
txtProductName.Text = grid.Cells[5].Value.ToString();
txtUnitPrice.Text = grid.Cells[6].Value.ToString();
txtRetailPrice.Text = grid.Cells[7].Value.ToString();
txtStockInHand.Text = grid.Cells[8].Value.ToString();
cmbCategory.SelectedValue = grid.Cells[9].Value;
cmbSupplier.SelectedValue = grid.Cells[10].Value;
chkIsTaxable.Checked = Convert.ToBoolean(grid.Cells[11].Value);
}
Populate Combobox. For the other combo boxes, I am using the same code
public static void FillCombo(List<QuantityDescriptionModel> quantityDescriptions, ComboBox control)
{
control.DataSource = quantityDescriptions;
control.ValueMember = "Id";
control.DisplayMember = "QtyDescription";
}
Screenshots attached
Data not loaded on cell_click
Data loaded without cell_click

Datagridview winforms cells doesnt get updated unless focus back on the grid

I am working with winforms c# datagridview and ran into a bug that I m not sure how to resolve. I have a datagridview in which the datasource is a datatable. The datagridview contains editable text fields and cellvaluechanged event as well as button column which I respond to thru a cellclick event. Currently when I change the value in a cell , hit the enter key to leave the just updated cell and click the button. The cellclick event which acts as the button click runs a task (TPL) in which the continuewith of the tasks updates values in the datagridview and that works because all the values that needed to be changed gets changed. The issue is that when I change a text value and don't hit the enter key and just immediately click the button on the row. the ui doesn't get updated intill I click on the cells to see the new values. I have looked this up and found that if I set the
datagridview.Currentcell = datagridview.Rows[e.RowIndex].Cells[4]
to the cells that I want to see the new values to. The new values appear. I don't want run for each cell I was wondering if there is a better way in handling this issue?
This is the code:
private void dgv_CellClick(object sender, DataGridViewCellEventArgs e)
{
//Button on grid
if (e.ColumnIndex == 17)
{
string val1 = dgv.Rows[e.RowIndex].Cells[3].Value.ToString();
string val2 = dgv.Rows[e.RowIndex].Cells[5].Value.ToString();
Task.Factory.StartNew<Dictionary<string, Response>>(() => GenerateData(val1, val2)).ContinueWith(ant => {
int rowId = Convert.ToInt32(this.dgv.Rows[e.RowIndex].Cells[1].Value);
SetResponse(rowId, this.DataSet.DataTable, ant.Result);
// i have tried the code below and it fixes the issue but don't want to go this route
//for (int i = 5; i < 12; i++) dgv.CurrentCell = dgv.Rows[e.RowIndex].Cells[i];
}, TaskScheduler.FromCurrentSynchronizationContext());
}
}
}
private void dgv_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 5)
{
string val1 = this.dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString().Trim();
if (!string.IsNullOrEmpty(val1))
{
//dgv.BeginEdit(false);
this.dgv.Rows[e.RowIndex].Cells[6].Value = DBNull.Value;
//dgv.EndEdit(DataGridViewDataErrorContexts.Commit);
}
}
}
By adding these two lines of code resolved the issue
this.dgv.EndEdit();
this.dgv.CurrentCell = null;

while getting an error user should not allow into another row/column in cell value

In my windows form I have validation tab control in my tab control implemented the data table with rows and columns if user give the duplicate name in second row/column same name as first row an error will come if user click on error button again user should be in same row and column user should not allow into another row/column so tell me how I can stop user do not allow into another cell if user get an error
please get the code in the cell leave event
You should add conditions to your data grid view's CellValidating event and call cancel if needed. Please refer to DataGridView.CellValidating Event
private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
dataGridView1.Rows[e.RowIndex].ErrorText = "";
// Don't try to validate the 'new row' until finished
// editing since there
// is not any point in validating its initial value.
if (dataGridView1.Rows[e.RowIndex].IsNewRow) { return; }
DataGridViewRow row = dataGridView1.Rows[e.RowIndex];
bool isValid = true;
// Convert grid view rows to an IEnumerable collection
IEnumerable<DataGridViewRow> _dataRows = dataGridView1.Rows.Cast<DataGridViewRow>();
// Loop through grid view rows
for (int i = 0; i < _dataRows.Count(); i++)
{
if(row.Cells[e.ColumnIndex].Value == _dataRows.ElementAt(i).Cells[e.ColumnIndex].Value)
{
isValid = false;
break; // To break from current loop
}
}
if (!isValid)
{
e.Cancel = true;
dataGridView1.Rows[e.RowIndex].ErrorText = "No duplicate values allowed.";
}
}
Why are you so specific about cell leave event. The best practice is to have dataGridView1_CellValidating event or dataGridView1_CellValueChanged.
If you need to get the value for comparing use.
var c = dataGridView1[e.ColumnIndex, e.RowIndex].Value; // got value and proceed for comparing.
in dataGridView1_CellValueChanged event

Show a message box when a data row is added to data grid view

As I cannot post to my previous question, I thought of posting it here.
This is my code to add a data row from text boxes to a datagridview. I want to show a message box when a data row is added.
My code works but always it does not show the message box for the first record. It shows 5 times the message box for the 6th record, 7 times for the 8th record. And I have a clear button in this form, when I click that also the row added message is getting displayed and shows for the number of times of the records that have in data gridview.
Can anyone find the error in this code..?
Here is my add button code.
//Add button code
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
//Create a new row in grid view
DataGridViewRow row = new DataGridViewRow();
//Create cells
row.CreateCells(this.myGrid, txtIdNum.Text, txtFname.Text, txtLname.Text, txtEmail.Text);
//add to data grid view
this.myGrid.Rows.Add(row);
//Throw mygrid_RowsAdded when a row is added.
myGrid.RowsAdded += new DataGridViewRowsAddedEventHandler(myGrid_RowsAdded);
}
catch(Exception xx)
{
MessageBox.Show(xx.Message);
}
}
Code for the add row event
// Row add event
void myGrid_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
MessageBox.Show("New record is added..");
txtIdNum.Text = "";
txtFname.Text = "";
txtLname.Text = "";
txtEmail.Text = "";
}
the first time btnAdd_Click is executed your event handler doesn't get executed because you set it after you add the row ... i suggest you swap your two lines of code like this:
myGrid.RowsAdded += new DataGridViewRowsAddedEventHandler(myGrid_RowsAdded);
this.myGrid.Rows.Add(row);
a better place for setting up the event handler would be in some initialisation code ... the way you do it results in getting more events for each click on the btnAdd button ...

All rows selected on clicked

I'm building a application in C# Winforms and using a Datagridview.
My problem is that when I click on a row, all rows are selected (without intention) and the application crashes (as the values inserted from the grid view selected row into labels are not intact (too many values...).
The correct behavior I'm looking for is the selection of on row only.
I thought the problem might be in the selectionMode (I used the value "RowHeaderSelect"), but I changed it, and the problem persisted, so it isn't it.
Do you have an idea what might be the problem ??
Not relying on much code, really, but here it is:
private void dgvCustomersList_MouseClick(object sender, MouseEventArgs e)
{
{
customerFunctions ChoosenRow = new customerFunctions(); //empty
DataGridViewRow dr = dgvCustomersList.SelectedRows[0];
ChoosenRow.CfirstName = dr.Cells[1].Value.ToString();
ChoosenRow.ClastName = dr.Cells[2].Value.ToString();
ChoosenRow.Caddress = dr.Cells[3].Value.ToString();
ChoosenRow.CcreditNumber = int.Parse(dr.Cells[7].Value.ToString());
ChoosenRow.CpersonalID = int.Parse(dr.Cells[5].Value.ToString());
}
}

Categories