Last RowHeader click on DataGridView - c#

In my C# windows forms program I would like to update the TextBoxes according to the RowHeader clicked on in the DataGridView:
if (e.RowIndex != -1 || e.ColumnIndex != -1)
{
fnameBox.Text = dgvPatient.Rows[rowIndex].Cells[0].Value.ToString();
mnameBox.Text = dgvPatient.Rows[rowIndex].Cells[1].Value.ToString();
lnameBox.Text = dgvPatient.Rows[rowIndex].Cells[2].Value.ToString();
mobnumBox.Text = dgvPatient.Rows[rowIndex].Cells[3].Value.ToString();
emailBox.Text = dgvPatient.Rows[rowIndex].Cells[4].Value.ToString();
bdate.Value = Convert.ToDateTime(dgvPatient.Rows[rowIndex].Cells[5].Value.ToString());
medHistBox.Text = dgvPatient.Rows[rowIndex].Cells[6].Value.ToString();
}
So, my problem is that the DataGridView shows an empty row at the end, so when I click on this header, the `Convert.ToDateTime statement throws an error and bugs the app. I tried checking if the result of conversion is null value... the code above is latest trial and it also failed.
How do I remove the error of clicking on the last RowHeader?

You should check null before using value and add try catch to your code. Should check cell value not null for all cells before ToString() dgvPatient.Rows[rowIndex].Cells[0].Value != null and use DateTime.TryParse instead of Convert.ToDateTime
try
{
fnameBox.Text = dgvPatient.Rows[rowIndex].Cells[0].Value != null ? dgvPatient.Rows[rowIndex].Cells[0].Value.ToString() : string.Empty;
mnameBox.Text = dgvPatient.Rows[rowIndex].Cells[1].Value.ToString();
lnameBox.Text = dgvPatient.Rows[rowIndex].Cells[2].Value.ToString();
mobnumBox.Text = dgvPatient.Rows[rowIndex].Cells[3].Value.ToString();
emailBox.Text = dgvPatient.Rows[rowIndex].Cells[4].Value.ToString();
DateTime date;
DateTime.TryParse(dgvPatient.Rows[rowIndex].Cells[5].Value.ToString(), out date);
//bdate.Value = Convert.ToDateTime(dgvPatient.Rows[rowIndex].Cells[5].Value.ToString());
medHistBox.Text = dgvPatient.Rows[rowIndex].Cells[6].Value.ToString();
}
catch (Exception e)
{
}

Related

Display if statement variable in messagebox

I'm having issues with displaying the variable within a Message box. What I want to do is display in a messagebox which Combobox hasn't been filled in, it will display this in a list within the messagebox and then stop the user from saving to the database. The error is stating that it is a use of an unassigned variable but I have assigned it at the top of the 'if' statement.
private void btnSaveDB_Click(object sender, EventArgs e)
{
if (cmbPolType.SelectedItem == null ||
cmbPolNum.SelectedItem == null ||
cmbTPReg.SelectedItem == null ||
cmbLossType.SelectedItem == null ||
cmbLossDesc.SelectedItem == null ||
cmbInsdFault.SelectedItem == null)
{
string polType, polNum, lossType, lossDesc, tpReg, insdFault = null;
if (cmbPolType.SelectedItem==null)
{
polType = "Policy Type";
}
if (cmbPolNum.SelectedItem==null)
{
polNum = "Policy Number";
}
if (cmbLossType.SelectedItem==null)
{
lossType = "Loss Type";
}
if (cmbLossDesc.SelectedItem ==null)
{
lossDesc = "Loss Description";
}
if (cmbTPReg.SelectedItem==null)
{
tpReg = "TP Reg";
}
if (cmbInsdFault.SelectedItem==null)
{
insdFault = "Insd at Fault";
}
MessageBox.Show("You have not selected options for the following: " + lossDesc );
}
No lossDesc is not initialized in that way as well as the other strings variables but the insdFault. (The error message points to lossDesc because is the only one used in the remainder of the code).
Instead of initializing each one, I suggest to use a simple List<string> where you add your error messages and type all of them at the end of the test
List<string> missingData = new List<string>();
if (cmbPolType.SelectedItem == null)
missingData.Add("Policy Type");
if (cmbPolNum.SelectedItem == null)
missingData.Add("Policy Number");
if (cmbLossType.SelectedItem == null)
missingData.Add("Loss Type");
if (cmbLossDesc.SelectedItem == null)
missingData.Add("Loss Description");
if (cmbTPReg.SelectedItem == null)
missingData.Add("TP Reg");
if (cmbInsdFault.SelectedItem == null)
missingData.Add("Insd at Fault");
if(missingData.Count > 0)
{
MessageBox.Show("You have not selected options for the following: " +
Environment.NewLine +
string.Join(Environment.NewLine, missingData.ToArray()));
}
else
{
... save to database ? ....
}
This removes the need to use and initialize a bunch of string variables and uses the string.Join method to get the whole error message in a single string with each error on a separate line.

C# If Else Inside For Loop Didn't Work

I am creating a web application to import an excel file into MS Dynamics Crm. Here is the code snippet
for (i = 0; i < dt.Rows.Count; i++)
{
if (dt.Rows[i][3].ToString() != String.Empty)
{
try
{
Entity contractline = new Entity("new_contractline");
contractline["new_lineitem"] = dt.Rows[i][1].ToString();
contractline["new_sublineitem"] = dt.Rows[i][3].ToString();
createChildData = service.Create(contractline);
string guidString = createChildData.ToString();
guidRecord[i] = guidString;
}
catch (Exception ex)
{
}
}
else if (dt.Rows[i][3].ToString() == string.Empty) /**THIS BLOK BELOW WON'T FIRE **/
{
try
{
Entity contractline = new Entity("new_contractline");
contractline["new_lineitem"] = dt.Rows[i][2].ToString();
contractline["new_sublineitem"] = dt.Rows[i][3].ToString();
contractline["new_quantity"] = "33";
service.Create(contractline);
}
catch (Exception ex)
{
}
}
The problem is that the else if block didn't fire when the dt.Rows[i][3] is empty. What could be the problem?
Why don't you just do else? If you don't have any other else-ifs.
if (dt.Rows[i][3].ToString() != String.Empty)
will fire if .ToString() is empty. However you will already get an exception here if dt.Rows[i][3] were null, because you can't ToString() on a null object. If you have a try catch outside of this code block, I suggest you check it out because dt.Rows[i][3] may be null and it is throwing the exception.
If you do have any other else-ifs, you should use
else if (string.IsNullOrWhiteSpace(dt.Rows[i][3].ToString()))
and change your if block (actually I suggest you do this in any case)
if (!string.IsNullOrWhiteSpace(dt.Rows[i][3].ToString()))
Reason being is that not all spaces are actually the space bar character. You might be getting other white space characters which will not trigger your String.Empty block because it is not empty. This will match a number of spaces which your cell might have. This will also catch invisible non-spacebar spaces. An example is the equivalent of the HTML code (non-breaking space) which is not actually the spacebar space (and will not match " ") but will occupy space.
Just use If...Else with string.IsNullOrEmpty(s) like below....
if (string.IsNullOrEmpty(dt.Rows[i][3].ToString()) == true)
{
// True.
Console.WriteLine("Null or empty");
}
else
{
Console.WriteLine("Not null and not empty");
}
Have you tried below?
else if (dt.Rows[i][3].ToString().Trim() == "")

validating a cell in a datagridview

I have a DataGridView in a Windows Form, it has 2 columns, the last column is going to contain the name of a packet, the point is that this name never has to be duplicated.
I tried with this code using CellValidating event
string value = Convert.ToString(dgvTiendas.Rows[e.RowIndex].Cells[e.ColumnIndex].Value);
int cellIndex = e.RowIndex;
if(cellIndex == 1)
{
foreach (DataGridViewRow rw in dgvTiendas.Rows)
{
if (cellIndex == rw.Index)
{
return;
}
else
{
string valorRow = Convert.ToString(rw.Cells["ContenedorCodigoBarras"].Value);
if (value == valorRow)
{
MessageBox.Show("The container is already used");
dgvTiendas.Rows[e.RowIndex].ErrorText = "Contenedor ya utilizado";
e.Cancel = true;
}
else
{
e.Cancel = false;
}
}
}
}
When i run the application and i write a container's name, it is validated but it seems that validate the current cell because the "Error text" appears on the RowHeader.
Please help i have some weeks with this.
You are having this problem because you are setting the error text of the row with this code.
dgvTiendas.Rows[e.RowIndex].ErrorText = "Contenedor ya utilizado";
You need to set error text of the cell
dgvTiendas[e.ColumnIndex, e.RowIndex].ErrorText = "an error occured";

Problems catching an exception in c#

I have a combobox with two items. I also have a button that opens a new form when one of these items are selected. However if none of the items are selected there is an exception(nullpointer). I have tried (to no avail) to catch this exception and show a mbox that prompts the user to choose one of the items.
Here is the code for the button click even:
if (labelGrid.Text == "Member" && cbTable.SelectedItem.ToString().Equals("Workout"))
{
string name;
string ss;
foreach (DataGridViewRow item in this.dtGrid1.SelectedRows)
{
ss = dtGrid1.CurrentCell.Value.ToString();
name = dtGrid1.SelectedCells[1].Value.ToString();
BookMemberWorkout bmw = new BookMemberWorkout(ss, name);
bmw.Label2.Text = ss;
bmw.Label1.Text = name;
bmw.ShowDialog();
}
}
You are not supposed to use exceptions for flow control in non-exceptional cases. The case that the user didn't select anything is surely not exceptional.
The correct approach would be a simple null check:
if(cbTable.SelectedItem == null)
{
// Show message box
}
else
{
// Your current code
}
Why your exception handling code isn't working is impossible to answer, because you didn't include it in your question.
I think the problem is in the line:
ss = dtGrid1.CurrentCell.Value.ToString();
You can't be sure the value is not null, so you should check it before calling the .ToString().
Instead of using a message box you could use a RequiredValidator to perform javascript validation, avoiding a useless postback.
From performance and readability point-of-view, I'd recommend checking for selected value in the combo box rather than catching an exception, like this
if(cbTable.SelectedItem == null)
{
MessageBox.Show("Please select a value in the combo box.");
return;
}
if (labelGrid.Text == "Member" && cbTable.SelectedItem.ToString().Equals("Workout"))
{
string name;
string ss;
foreach (DataGridViewRow item in this.dtGrid1.SelectedRows)
{
ss = dtGrid1.CurrentCell.Value.ToString();
name = dtGrid1.SelectedCells[1].Value.ToString();
BookMemberWorkout bmw = new BookMemberWorkout(ss, name);
bmw.Label2.Text = ss;
bmw.Label1.Text = name;
bmw.ShowDialog();
}
}
However to answer your specific query, you can catch NullReferenceException like this:
try{
if (labelGrid.Text == "Member" && cbTable.SelectedItem.ToString().Equals("Workout"))
{
string name;
string ss;
foreach (DataGridViewRow item in this.dtGrid1.SelectedRows)
{
ss = dtGrid1.CurrentCell.Value.ToString();
name = dtGrid1.SelectedCells[1].Value.ToString();
BookMemberWorkout bmw = new BookMemberWorkout(ss, name);
bmw.Label2.Text = ss;
bmw.Label1.Text = name;
bmw.ShowDialog();
}
}
}
catch(NullReferenceException ex)
{
MessageBox.Show("Please select a value in the combo box.");
}

c# if else statement

I have a problem here because my coding is not working(error) and I don't know how to correct it.Can you guys check if this statement right or wrong? My conditions is
1)if textbox productname is null or empty and dropdownlist1 not selected, text will null.
2)if textbox productname is filled(string) then text will filled in
3)if if textbox productname is null or empty and dropdownlist1 selected, text will select value.
Refer bold text.THANKS!!
if (String.IsNullOrEmpty(txtSearchProductname.Text) == true)
{
if (**DropDownList1.SelectedValue.ToString == null**)
{
txtSearchProductname.Text = " ";
}
else
{
SqlProductmaster.InsertParameters["ProductName"].DefaultValue = DropDownList1.SelectedValue.ToString();
}
}
else
{
SqlProductmaster.InsertParameters["ProductName"].DefaultValue = txtProductName.Text.ToString();
}
Two issues:
You have ToString, not ToString(). ToString refers to the function itself; you need the parentheses to invoke the method
You should not be calling ToString() at all, since the value may be null; this will generate a NullReferenceException. Just check if DropDownList1.SelectedValue == null.
This should be all you need:
if (String.IsNullOrEmpty(txtSearchProductname.Text))
{
if (DropDownList1.SelectedValue == null)
{
txtSearchProductname.Text = " ";
}
else
{
SqlProductmaster.InsertParameters["ProductName"].DefaultValue = DropDownList1.SelectedValue;
}
}
else
{
SqlProductmaster.InsertParameters["ProductName"].DefaultValue = txtProductName.Text;
}
.ToString is a method. You want to check the result of calling that method, so you need to call it (hence, .ToString()).
You don't need that many ToString. If DropDownList1.SelectedValue is null, then DropDownList1.SelectedValue.ToString() will throw an exception.
if (string.IsNullOrEmpty(txtSearchProductname.Text) == true)
{
if (DropDownList1.SelectedValue == null)
{
txtSearchProductname.Text = " ";
}
else
{
SqlProductmaster.InsertParameters["ProductName"].DefaultValue = DropDownList1.SelectedValue;
}
}
else
{
SqlProductmaster.InsertParameters["ProductName"].DefaultValue = txtProductName.Text;
}
The first thing I see is that you have a ToString method without the parenthesis. It should look like this:
if (DropDownList1.SelectedValue.ToString() == null)
As others have pointed out, the second issue is the comparison to null after converting the item to a string. Converting a null to a string will cause an error (the string representation of a null doesn't exist). Instead, as they indicated, you should remove the ToString() entirely and compare the SelectedValue to null like so:
if (DropDownList1.SelectedValue == null)
You are using the SelectedValue of the DropDownList with a ToString() which is not needed. See below.
if (String.IsNullOrEmpty(txtSearchProductname.Text) == true)
{
if (string.IsNullOrEmpty(DropDownList1.SelectedValue))
{
txtSearchProductname.Text = " ";
}
else
{
SqlProductmaster.InsertParameters["ProductName"].DefaultValue = DropDownList1.SelectedValue;
}
}
else
{
SqlProductmaster.InsertParameters["ProductName"].DefaultValue = txtProductName.Text.ToString();
}
HTH

Categories

Resources