c# if else statement - c#

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

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() == "")

How to handle empty session which always gives exception in asp.net C#?

Whenever my data in Session is empty it always go into exception, I've to handle this flow using try catch flow,
try
{
Username = Session["Username"].ToString();
}
catch(Exception e)
{
Username = "";
}
is there anything from which I can check if session is empty or not. I think this is not a good way to handle this thing.
Before calling ToString check for null
try
{
if(Session["Username"] != null)
Username = Session["Username"].ToString();
}
catch(Exception e)
{
Username = "";
}
You can use ternary conditional operator as well and you wont need the try-catch block.
Username = Session["Username"] == null ? "" Session["Username"].ToString();
Instead of using ToString() you can use Convert.ToString().
string username = Convert.ToString(Session["Username"]);
If Session["Username"] is null, it will return an empty string.
I prefer add a wrapper property for a session.
public string Username
{
get{ if(Session["Username"]!=null) return Session["Username"].ToString() else return String.Empty; }
set{ Session["Username"] = value; }
}
Well you can use string class to check if the string in the session is NULL or not.
you can implement like this.
if (string.IsNullOrEmpty((string)Session["Username"]))
{
//do your stuff
Username = Session["Username"].ToString();
}
Hope this will help you.
You can use this :
try
{
if(Session["Username"]!=null)
{
Username = Session["Username"].ToString();
}
}
catch(Exception e)
{
Username = "";
}
Try like this
try
{
if(Session["Username"] != null)
{
Username = Session["Username"].ToString();
}
}
else
{
//Do Something else
}
to avoid null pointer exception you should be using
Convert.ToString(Session["Username"]);
Rather than
Session["Username"].ToString();
As Convert.ToString() handles null results also.

How to fix a boolean method that returns true everytime asp.net

I designed my webpage to read a data string then display the results on labels in an html table. I am attempting to highlight the row that my database reads as a current order. My only problem is only one record is set to be active but they all highlight as if they were active. I use an array to set my data and I also use the label to get the ID I need (all is in code below). I have posted my method and where I use it in the asp page load. How can I fix my method to return correctly?
The implementing of the method in page load
if (lineData.IsCurrentOrderFind(L68.Text))
{
myTable.Rows[1].Cells[0].BgColor = "#FE2E2E";
myTable.Rows[1].Cells[1].BgColor = "#FE2E2E";
myTable.Rows[1].Cells[2].BgColor = "#FE2E2E";
myTable.Rows[1].Cells[3].BgColor = "#FE2E2E";
myTable.Rows[1].Cells[4].BgColor = "#FE2E2E";
}
Here is method that label above gets passed to
public bool IsCurrentOrderFind(string itemNumber)
{
StringBuilder sqlString = new StringBuilder();
sqlString.Append("SELECT * ");
sqlString.Append("FROM WorkOrder ");
sqlString.Append("WHERE LineNumber = " + ConfigurationManager.AppSettings["Line"] + " AND LineCompleted = 0 AND (ScaleGroup LIKE '%1' OR ScaleGroup LIKE '%3') ");
sqlString.Append(" AND CaseGenNum6 = #CaseGenNum6");
SqlDataReader reader = null;
SqlConnection dbConn = App_Code.DBHelper.getConnection();
SqlParameter[] parameters = new SqlParameter[] { new SqlParameter("#CaseGenNum6", itemNumber) };
try
{
reader = App_Code.DBHelper.executeQuery(dbConn, sqlString.ToString(), parameters);
while (reader.Read())
{
IsCurrentOrder = (reader["IsCurrentOrder"] != DBNull.Value && !string.IsNullOrEmpty(reader["IsCurrentOrder"].ToString())) ? true : false;
}
reader.Close();
reader.Dispose();
dbConn.Close();
dbConn.Dispose();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (dbConn != null)
{
try { dbConn.Close(); dbConn.Dispose(); }
catch { }
}
if (reader != null)
{
try { reader.Close(); reader.Dispose(); }
catch { }
}
}
if (IsCurrentOrder == true) I realize this is not necessary
{
return true;
}
else
{
return false;
}
}
The problem could be with this expression:
!string.IsNullOrEmpty(reader["IsCurrentOrder"].ToString())
Instead of calling ToString(), try simply casting it to a string:
!string.IsNullOrEmpty((string)reader["IsCurrentOrder"])
Possibly even better (the previous line might throw an exception if it's not really a string):
!string.IsNullOrEmpty(reader["IsCurrentOrder"] as string)
The reason being is that if the string is really null, calling ToString() will return a non-null string "null".
IsCurrentOrder is not declared locally. It seems to be declared at a higher scope. When you enter this function, nothing is initializing the variable (back to false). So, it is remaining at its last setting. Try this code instead:
public bool IsCurrentOrderFind(string itemNumber)
{
bool IsCurrentOrder = false;
//and the rest of your source code
the line
IsCurrentOrder = (reader["IsCurrentOrder"] != DBNull.Value && !string.IsNullOrEmpty(reader["IsCurrentOrder"].ToString())) ? true : false;
}
It's not actually checking the value of the field, only that it's not null or empty.
Try
if(
(reader["IsCurrentOrder"] != DBNull.Value
&&
!string.IsNullOrEmpty(reader["IsCurrentOrder"].ToString()))
)
{
IsCurrentOrder = reader["IsCurrentOrder"];
}
else
IsCurrentOrder = false;
I think there is a lot of refactoring you could do to this method though that will simplify the logic.

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.");
}

Categories

Resources