I need help on allowing my textbox data entered to only be in the field between A-H and then displayed to a listbox. This is my code so far, thank you. I can still select letters outwith A-H, yet I get an error message no matter what letter I select. I need it so I can only select A-H and if I select anything outwith that it displays an error message.
try
{
if (!this.TxtCoach.Text.Contains('A') ||
!this.TxtCoach.Text.Contains('B') ||
!this.TxtCoach.Text.Contains('C') ||
!this.TxtCoach.Text.Contains('D') ||
!this.TxtCoach.Text.Contains('E') ||
!this.TxtCoach.Text.Contains('F') ||
!this.TxtCoach.Text.Contains('G') ||
!this.TxtCoach.Text.Contains('H'))
{
throw new ArgumentException("Correct your coach is valid!");
}
}
catch (ArgumentException ex)
{
MessageBox.Show(ex.Message);
}
LstFinalB.Items.Add(TxtCoach.Text);
You can use this to validate the data entered in the input box.
public bool IsAccepted(String textToValidate)
{
Regex strPattern = new Regex("^[a-hA-H]*$");
if (!strPattern.IsMatch(textToValidate))
{
return false;
}
return true;
}
Here is a screenshot of how I tested it via a Console app:
try
{
if (this.TxtCoach.Text.Contains('A') ||
this.TxtCoach.Text.Contains('B') ||
this.TxtCoach.Text.Contains('C') ||
this.TxtCoach.Text.Contains('D') ||
this.TxtCoach.Text.Contains('E') ||
this.TxtCoach.Text.Contains('F') ||
this.TxtCoach.Text.Contains('G') ||
this.TxtCoach.Text.Contains('H'))
{
LstFinalB.Items.Add(TxtCoach.Text);
}
else
{
throw new ArgumentException("Correct your coach is valid!");
}
}
catch (ArgumentException ex)
{
MessageBox.Show(ex.Message);
}
Your If statement logic was wrong and you would never have a correct input, and the Listbox.Items.Add(Item) was also in the wrong place.
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.
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.
Can any one of you fine folks tell me what would possibly be causing this C# method to throw an IndexOutOfBounds exception? It would be much appreciated.
public bool PopulateStudents(string path) //decided to return bool if successful reading file.
{
theStudentList = new List<Student>(); //create instance..
string text = null;
FileInfo source = new FileInfo(#path);
bool success = true;
try
{
StreamReader r = source.OpenText();
text = r.ReadLine();
string[] splitText = new string[23];
Student currentStudent = new Student();
while (text != null)
{
splitText = text.Split(',');
currentStudent = new Student(splitText[0], splitText[1], splitText[2]);
for (int i = 0; i < 20; i += 2)
{
currentStudent.EnterGrade(int.Parse(splitText[i + 3]), int.Parse(splitText[i + 4]));
}
currentStudent.CalGrade();
theStudentList.Add(currentStudent);
text = r.ReadLine();
}
r.Close();
}
catch (Exception exc)
{
success = false;
Console.WriteLine(exc.Message);
}
return success;
}
Sample input file:
0199911,Bill,Gates,27,30,56,60,0,30,83,100,57,60,0,30,59,60,0,30,59,60,88,100
0199912,Steve,Jobs,30,30,55,60,25,30,70,100,55,60,25,30,50,60,0,30,58,60,80,100
0199913,Marc,Andresen,30,30,55,60,25,30,70,100,55,60,25,30,50,60,0,30,58,60,80,100
0199914,Larry,Ellisen,30,30,55,60,25,30,70,100,55,60,25,30,50,60,0,30,58,60,80,100
EDIT: All of your answers are great and much appreciated, but as it turns out I just had some empty blank space at the end of my text file. I would like to point out that the responses you provided would fix this problem if I were to keep the blank space at the end. :)
Whenever you read a line with less than 23 commas. Most likely this is an empty line in the end.
You should do
if (splitText.Length<24)
{
WarnLogOrDoSomethingElse(text);
continue;
}
immediately after
splitText = text.Split(',');
The problem is that when you assign the return of text.Split(',') to splitText you are replacing your array of length 23 with an array that has a length equal to the number of tokens that result from splitting the text. You need to check how many items are now in your array before accessing specific items and the loop should probably use splitText.Length as an upper bound.
Well when you say:
splitText = text.Split(', ');
You presume further down your loop that your always going to get 23 elements I suspect this might not always be the case.
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