I have this codes:
private string ErrorMessage(string input)
{
{
if (!string.IsNullOrEmpty(input))
return input;
BtnImport1.Visible = false;
}
return "No value entered!";
}
protected void btnUpload_Click(object sender, EventArgs e)
{
string strFileNameOnServer = fileUpload.PostedFile.FileName;
string fileExt =
System.IO.Path.GetExtension(fileUpload.FileName);
if (fileUpload.PostedFile != null && fileExt == ".csv")
{
try
{
fileUpload.PostedFile.SaveAs(Server.MapPath("~/Uploads"));
Label1.Text = "File name: " +
fileUpload.PostedFile.FileName + "<br>" +
fileUpload.PostedFile.ContentLength + " kb<br>" +
"Content type: " +
fileUpload.PostedFile.ContentType;
}
catch (Exception ex)
{
Label1.Text = "Error saving <b>" + strFileNameOnServer + "</b><br>. " + ex.Message;
}
BtnImport1.Visible = true;
Cancel.Visible = true;
fileUpload.Visible = false;
btnUpload.Visible = false;
}
else
{
Label1.Text = "Error - a file name must be specified/only csv files are allowed";
return;
}
var data = File.ReadAllLines(Server.MapPath("~/Uploads"))
.Select(line => line.Split(','))
.Select(columns => new { GuestID = ErrorMessage(columns[0]), IC_No = ErrorMessage(columns[1]), Grouping = ErrorMessage(columns[2]), Remarks = ErrorMessage(columns[3]), GuestName = ErrorMessage(columns[4]), Class_Group = ErrorMessage(columns[5]), Staff = ErrorMessage(columns[6]), Attendance_Parents_Only = ErrorMessage(columns[7]), Registration = ErrorMessage(columns[8]) });
myGridView.DataSource = data;
myGridView.DataBind();
}
Currently, if there are empty fields in the gridview, it will display “No value entered”, but, this is only for column[1] to column [7]. If I were to upload the csv file with column[8] and column[0] containing no value, the debugger would stop as there is an error. How do I avoid this? Please help!
Change this line:
To this:
UPDATE: Expanding my answer to answer second question.
Change your ErroMessage method to this:
And also change the var data… part to this (pay attention how I pass columns[7] & columns[8] to the ErrorMessage method):
Explanation: I rewrote the ErrorMessage function to receive an extra optional parameter (defaulted to “string”) called dataTypeExpected. You can use that parameter to indicate the data type that the input parameter should be in. If the data passed in is an empty string or a string that does not contain digits and you specify the dataTypeExpected parameter to be “int” (as I did above), the error message will say “Error: value must be an integer”;
Notice that I removed the line
BtnImport1.Visible = false;from the ErrorMessage method because you are executing that line once for every time the ErrorMessage is called when you only need to execute it once. So, move that line to some place else.