Automatic null values in database if textbox is empty - c#

I want to have null values in my table when the user has left the textbox empty. I'm doing this with a array and a for loop:
private void AddQuestion()
{
string [] checkinput= new string[] { txtBxQuestionCat.Text, txBxQuestion.Text };
string[] countinput= new string[2];
if (String.IsNullOrEmpty(txtBxQuestionCat.Text) && String.IsNullOrEmpty(txBxQuestion.Text))
{
ExceptiesException ex = new ExceptiesException("error");
throw ex;
}
for (int i = 0; i < countinput.Length; i++)
{
if (checkinput[i] == "")
{
countinput[i] = null;
}
}
try
{
qa = new HR5DataSetTableAdapters.QueriesTableAdapter();
qa.AddQuestion(countinput[0], countinput[1]);
hR5DataSetQuestionTableAdapter.Fill(hR5DataSet.question);
questionViewSource1.View.MoveCurrentToLast();
MessageBox.Show("add complete");
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
This should be working, but when I'm adding a questioncat and a question and load it into my datagrid, the new questioncat and question has not added to the database, only a new QuestionId. I think it is because I say countinput[i] = null, but I don't know how I could also say that the values need to be null if de textboxes are empty.

You don't need the countinput variable. Alter the for loop after the "both empty" check to
for (int i = 0; i < checkinput.Length; i++)
if (checkinput[i] == "")
checkinput[i] = null;
and then add the question with
qa.AddQuestion(checkinput[0], checkinput[1]);
Currently you are always entering null values, and ignoring the user input.

Related

Add 2 parameters to Email Template Body

I have a email template and i have bind 1 parameter to it(this.OrderCode) and it's working .So now i need to bind another one.
Email Template Like Below,
string OrderTemplate="<p><%=this.OrderCode%></p><p><%=this.ReferredTo%></p>";
tempValues comes like below,
[0]this.OrderCode
[1]ODR5000
[2]this.ReferredTo
[3]Janez Smithson
Using below code i need to show both of above values.In here only shows 1st value only(ODR5000)
public string EmailTemplate(string OrderTemplate, params string[] tempValues)
{
string templatebody = string.Empty;
try
{
templatebody = OrderTemplate;
for (var i = 0; i < tempValues.Length; i++)
{
templatebody= templatebody.Replace("<%={0}%>".FormatWith(tempValues[i]), tempValues++);
}
}
catch (Exception ex)
{
throw ex;
Log4NetLogger.Log(ex);
}
return templatebody;
}
I have pretty similar function for that.
for (int i = 0; i < tempValues.Length; i++)
{
var pattern = string.Format(#"(\[{0}\])", i);
templatebody = Regex.Replace(templatebody, pattern, tempValues[i].ToString());
}

Setting Controls in Classes

I'm trying a booking system, I want to put controls on the booking aspect. I want to use If and then cases. I want to control in such a way that if number of booking is 4, then it will throw an exception and stop inserting in the database.
public ApiResult<TimeModelExtended> SaveBooking(Booking booking)
{
AchimotaGCDb repo = new AchimotaGCDb();
var result = new ApiResult<TimeModelExtended>();
try
{
booking.PlayDate = getPlayDate(booking.RefCode);
Int16 nb = getNbBooked(booking.RefCode);
if (nb == 4)
{
Exception ex = new Exception();
result.Successfull = 0;
result.InternalError = ex.Message;
result.Error = "Booking slot is full";
}
else if (nb == 0)
{
booking.BookingStatus = 1;//Booked already
}
else
{
booking.BookingStatus = 0;//Reservation already
}
repo.Insert(booking);
result.Successfull = 1;
result = GetOneteeTime(booking.RefCode);
}
catch (Exception ex)
{
result.Successfull = 0;
result.InternalError = ex.Message;
result.Error = "Error from server";
}
finally
{
repo.Dispose();
}
return result;
}
help to solve that.
If you want to throw an exception, you need to really throw it:
if (nb == 4)
{
throw new Exception("Booking slot is full.");
}
But I don't think throwing an exception is a good idea. Throwing an exception and validation is a different thing.
Here is my suggestion:
if (nb == 4)
{
return result = new ApiResult<TimeModelExtended>()
{
Successfull = 0,
InternalError = "Other messages",
Error = ""Booking slot is full."
};
}
This will return as result message that nothing will continue unless you satisfy that nb != 4

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.

Confused on Updating Table using DataGrid

-Image on top Codes Below....
private void Save_FGARec()
{
try
{
for(int x= 0; x < FGAdataGrid.Rows.Count; x++)
{
sysSFCDBDataContext SFC = new sysSFCDBDataContext();
Sales_FGAllocated FGA = SFC.Sales_FGAllocateds.FirstOrDefault(r => r.RowID == Convert.ToInt64(FGAdataGrid.Rows[x].Cells[0].Value));
if (FGAdataGrid.Rows[x].Cells[0].Value != null)
{
FGA.TotalLoaded = Convert.ToInt64(FGAdataGrid.Rows[x].Cells[6].Value);
SFC.SubmitChanges();
}
else
{
SFC.Connection.Close();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
-- Is my Code on Update Right? I'm confuse coz my table doesn't update what i store on this column totalloaded which counts as cell[8]... did i missed something here?
try below, not sure this will solve the issue, but may be you are not dispose/ close the data context correctly with current code. you can use using block like below
using (sysSFCDBDataContext SFC = new sysSFCDBDataContext())
{
Sales_FGAllocated FGA = SFC.Sales_FGAllocateds.FirstOrDefault(r => r.RowID == Convert.ToInt64(FGAdataGrid.Rows[x].Cells[0].Value));
if (FGAdataGrid.Rows[x].Cells[0].Value != null)
{
FGA.TotalLoaded = Convert.ToInt64(FGAdataGrid.Rows[x].Cells[6].Value);
SFC.SubmitChanges();
}
}

IndexOutOfRangeException when trying to create an Object from a text file in C#

I'm currently in the middle of trying to take a '|' delimited text file and create objects from the data contained within. Example:
Name|Address|City|State|Zip|Birthday|ID|Etc.
Name2|Address2|City2|State2|Zip2|Birthday2|ID2|Etc.
The newly created object, is then added to a list of said objects and the program moves to the next line of the file by way of a while loop using .Peek() (to make sure I don't go past the end of the file).
However, when it gets to creating the second object (more specifically, the second field of the second object), it throws an Index Out Of Range Exception, and I can't for the life of me figure out why. Thank you whomever might read this!
StreamReader textIn = new StreamReader(new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read));
List<Student> students = new List<Student>();
while (textIn.Peek() != -1)
{
string row = textIn.ReadLine();
MessageBox.Show(row);
string [] fields = row.Split('|');
Student temp = new Student();
try
{
temp.name = fields[0];
temp.address = fields[1];
temp.city = fields[2];
temp.state = fields[3];
temp.zipCode = Convert.ToInt32(fields[4]);
temp.birthdate = fields[5];
temp.studentID = Convert.ToInt32(fields[6]);
temp.sGPA = Convert.ToDouble(fields[7]);
}
catch
{
MessageBox.Show("IndexOutOfRangeException caught");
}
students.Add(temp);
}
textIn.Close();
First you can't ensure if its a IndexOutOfRange Exception with your current catch block.
catch
{
MessageBox.Show("IndexOutOfRangeException caught");
}
It can be anything, may be exception during parsing to double. You may modify your catch block to:
catch(IndexOutOfRangeException ex)
{
MessageBox.Show(ex.Message);
}
Also if you are going to access fields[7] then its better if you can check against the length of array to ensure that you got atleast 8 elements in your array.
if(fileds.Length >=8)
{
temp.name = fields[0];
....
To catch FormatException which can occur during double parsing you may add an extra catch block for:
catch (FormatException ex)
{
MessageBox.Show(ex.Message);
}
Check if you have all 8 fieds in a line.
Show a message if ther isn't.
Get the actual exception and show its message to see the real problem description.
Use Double.TryParse Method and Int32.TryParse Method to be sure all numeric values are valid
Also use while (!textIn.EndOfStream) instead.
try
{
int tempInt;
double tempDouble;
if (fields.Length = 8)//#1
{
temp.name = fields[0];
temp.address = fields[1];
temp.city = fields[2];
temp.state = fields[3];
if (!int.TryParse(fields[4], out tempInt)) //#4
temp.zipCode = tempInt;
else
{
//..invalid value in field
}
temp.birthdate = fields[5];
if (!int.TryParse(fields[6], out tempInt)) //#4
temp.studentID = tempInt;
else
{
//..invalid value in field
}
if (!int.TryParse(fields[7], out tempDouble)) //#4
temp.sGPA = tempDouble;
else
{
//..invalid value in field
}
}
else //#2
{
MessageBox.Show("Invalid number of fields");
}
}
catch (Exception ex) //#3
{
MessageBox.Show(ex.Message);
}
Maybe ReadAllLines will work a bit better if the data is on each line:
List<Student> students = new List<Student>();
using (FileStream textIn = new FileStream(path, FileMode.Open, FileAccess.Read))
{
foreach (string line in File.ReadAllLines(path))
{
MessageBox.Show(line);
string[] fields = line.Split('|');
Student temp = new Student();
try
{
temp.name = fields[0];
temp.address = fields[1];
temp.city = fields[2];
temp.state = fields[3];
temp.zipCode = Convert.ToInt32(fields[4]);
temp.birthdate = fields[5];
temp.studentID = Convert.ToInt32(fields[6]);
temp.sGPA = Convert.ToDouble(fields[7]);
}
catch
{
MessageBox.Show(string.Format("IndexOutOfRangeException caught, Split Result:", string.Join(", ", fields.ToArray())));
}
students.Add(temp);
}
}
In the given data if you have atleast eight columns for every row, you wont be getting index of of range exception but parsing of item at 4, 6, 7 would fail as they are not numbers and converting the non number values to int and double raises the exception.
temp.zipCode = Convert.ToInt32(fields[4]);
temp.studentID = Convert.ToInt32(fields[6]);
temp.sGPA = Convert.ToDouble(fields[7]);
You need to change the catch block to know the reason for exception
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}

Categories

Resources