How to display error lines from a gridview? - c#

I have these codes for uploading csv file. Also, I have put a GridView to display its contents. Now, what I want to do is to display error lines from the GridView, for example, if there are missing words in a particular column or row, I would want to display that that particular line is empty, and that the user has to reupload with that particular line updated. The thing is, I'm really new with this, I hope someone could help me! I do not know how to retrieve the error lines and display it on the website. These are my codes :
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(ConfigurationManager.AppSettings + appDataPath + "\\" + strFileNameOnServer);
fileUpload.PostedFile.SaveAs(Server.MapPath("~/Uploaded"));
//string appPath = HttpContext.Current.Request.ApplicationPath;
// string physicalPath = HttpContext.Current.Request.MapPath("~/MajorProject");
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("~/Uploaded"))
.Select(line => line.Split(','))
.Select(columns => new {GuestName = columns[0], Guest_ID = columns[1], IC_Number = columns[2]});
myGridView.DataSource = data;
myGridView.DataBind();
}
Do I have to add new items into my aspx file? Like a label to display the error lines? The contents of the csv file has Name, Ic Number and also House. If so, can anyone show me the codes to do this?

You could check for missing values on GridView.RowDataBound event for yours myGridview.
Example:
void myGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
// Check if any of the values of mygridview row cells are empty.
if (e.Row.Cells[0].Text == "")
{
e.Row.Cells[0].Text = "ERROR: Guest name is empty!"
e.Row.Cells[0].Attributes.CssStyle.Add(HtmlTextWriterStyle.Color, "red");
}
if (e.Row.Cells[1].Text == "")
{
e.Row.Cells[1].Text = "ERROR: Guest Id is empty!"
e.Row.Cells[1].Attributes.CssStyle.Add(HtmlTextWriterStyle.Color, "red");
}
if (e.Row.Cells[2].Text == "")
{
e.Row.Cells[2].Text = "ERROR: Ic number is empty!"
e.Row.Cells[2].Attributes.CssStyle.Add(HtmlTextWriterStyle.Color, "red");
}
}
}
Don't forget to declare it inside gridview properties:
<asp:GridView ID="myGridview"
runat="server"
OnRowDataBound="myGridView_RowDataBound">
</asp:GridView>

Related

Jquery Id parameter get wrong

I cannot see what is wrong here:
Javascript
function showDialogBox(dialogText, atomicId) {
if (dialogText.text == "")
{
dialogText = "¿Do you want to continue?";
}
if ($('#' + atomicId).text() != "")
{
return confirm(dialogText);
}
else
{
return true;
}
}
The Label HTML
<asp:Label ID="AtomicId" ClientIDMode="Static" runat="server" CssClass="datalabel DHidden" />
I checked atomicId param and its "AtomicId" string, but when I check $('#' + atomicId).text, it returns:
alert($('#' + atomicId).text);
What!!??. The text of the Label AtomicId is supposed to be empty the first call.
I updated it with the rest of my code where I call the function. Anyway Shobhit Walia solved it.
protected void GridDecisionsView_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[0].Attributes.Add("style", "display:none");
e.Row.Cells[1].Attributes.Add("style", "display:none");
e.Row.Cells[2].Attributes.Add("style", "display:none");
e.Row.Cells[3].Attributes.Add("style", "display:none");
if (e.Row.RowIndex != -1)
e.Row.Attributes.Add("onclick", "if(showDialogBox('" + getDialogString() + "', '" + AtomicId.ID + "')){"
+ CSM.GetPostBackEventReference((Control)sender, "Select$" + e.Row.RowIndex.ToString()) + "}");
}
Thanks,
Try with these
function showDialogBox(dialogText, atomicId) {
if (dialogText == "")
{
dialogText = "¿Do you want to continue?";
}
if ($('#' + atomicId).text() != "")
{
return confirm(dialogText);
}
}

Search from SqlDataSource show in Gridview asp.net c#

I have problem about my label is not lost when search data that have in SQL Server.
Here is my code
protected void btnSearchAll_Click(object sender, EventArgs e)
{
// BindAbb();
string search1 = txtSearch.Text;
string Filter = "";
if (SqlDataSource1.SelectCommand.Contains(String.Empty))
{
lblOutput.Visible = true;
lblOutput.Text = "Not Found";
}
if (search1 != "")
{
Filter = Filter + "AbbCode like '%" + search1 + "%' and ";
}
if (Filter.Length > 0)
{
string finalFilter = Filter.Remove(Filter.Length - 4, 3);
SqlDataSource1.FilterExpression = finalFilter;
}
else
{
lblOutput.Visible = false;
grd_AbbCode.DataBind();
}
}
}
When I search data that don't have in SQL Server, it's ok when "Not Found" is show on my page.
http://www.mx7.com/i/ece/0u4iX8.jpg
but when I search data that I do have in SQL Server, "Not found" is still show together with my data.
http://www.mx7.com/i/125/AxrUNz.jpg
I solve it in my way but it still show.
How to solve it? Thank you so much.

How to use validation in DataGridView

In my program, when I click a particular row in DataGridView, if that row contains "\" it should pop up an error message that "\ is not allowed in name or in path". I don't know how to do that.
Here is the code:
namespace OVF_ImportExport
{
public partial class Form1 : Form
{
string sName = "";
string sPath = "";
public Form1()
{
InitializeComponent();
}
private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
sName = row.Cells[0].Value.ToString();
sPath = row.Cells[1].Value.ToString();
}
}
private void BtnCreate_Click(object sender, EventArgs e)
{
richTextBox1.Text = "";
StreamWriter file = new StreamWriter("Export.bat");
file.WriteLine("c: ");
file.WriteLine("cd \\");
file.WriteLine("cd Program Files ");
file.WriteLine("cd VMware");
file.WriteLine("cd VMware OVF Tool");
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
sName = row.Cells[0].Value.ToString();
sName = sName.Trim();
sPath = row.Cells[1].Value.ToString();
file.WriteLine("start ovftool.exe --powerOffSource vi://" + TxtUsername.Text + ":" + TxtPassword.Text + "#"
+ TxtIP.Text + sPath + " " + "\"" + TxtBrowsepath.Text + "\\" + sName + "\\" + sName + ".ovf" + "\"" + Environment.NewLine);
}
file.WriteLine("pause");
MessageBox.Show("Batch File Created","Batch File");
file.Close();
}
try using this:
// Attach DataGridView events to the corresponding event handlers.
this.dataGridView1.CellValidating += new DataGridViewCellValidatingEventHandler(dataGridView1_CellValidating);
method for above event handler:
private void dataGridView1_CellValidating(object sender,
DataGridViewCellValidatingEventArgs e)
{
// Validate the CompanyName entry by disallowing empty strings.
if (dataGridView1.Columns[e.ColumnIndex].Name == "CompanyName")
{
if (String.IsNullOrEmpty(e.FormattedValue.ToString()))
{
dataGridView1.Rows[e.RowIndex].ErrorText =
"Company Name must not be empty";
e.Cancel = true;
}
}
}

Saving multiple pieces of form input to a file

What would be the best way to save a windows form to a file with a few text boxes collecting user input. I using this at the moment:
if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
File.WriteAllText(saveFileDialog1.FileName, tB1.Text);
File.WriteAllText(saveFileDialog1.FileName, tB2.Text);
}
This is fine for saving the input from the first text box but when it comes to the other it wont save the data entered.
If it was me I would use the StreamWriter / StreamReader Classes since they have WriteLine and Readline methods respectively.
i.e. something like this
private void button1_Click(object sender, EventArgs e)
{
if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
using (StreamWriter sw = new StreamWriter(saveFileDialog1.FileName))
{
sw.WriteLine(tB1.Text);
sw.WriteLine(tB2.Text);
sw.WriteLine(tB3.Text);
sw.WriteLine(tB4.Text);
sw.Close();
}
}
}
private void button2_Click(object sender, EventArgs e)
{
if(openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
using (StreamReader sr = new StreamReader(openFileDialog1.FileName))
{
tB1.Text = sr.ReadLine();
tB2.Text = sr.ReadLine();
tB3.Text = sr.ReadLine();
tB4.Text = sr.ReadLine();
sr.Close();
}
}
}
Concatenate this two texbox then;
File.WriteAllText(saveFileDialog1.FileName, tB1.Text + Environment.NewLine + tB2.Text );
how about concatenating the two textboxes? for clarity,
string forSaving = tB1.Text + "\n" + tB2.Text;
File.WriteAllText(saveFileDialog1.FileName, forSaving);
or
File.WriteAllText(saveFileDialog1.FileName, tB1.Text + "\n" + tB2.Text);
UPDATE 1
string firstName = "FirstName: " + txtFirstName.Text;
string lastName = "LastName: " + txtLastName.Text;
string personAddress = "FirstName: " + txtAddress.Text;
string details = firstName + "\n" + lastName + "\n" + personAddress;
File.WriteAllText(saveFileDialog1.FileName, tB1.Text + "\n" + details);
The best way would probably be to create a method in your form that will return a string with all of the values from the TextBoxes into whatever format you want. Something like this would work:
File.WriteAllText(saveFileDialog1.fileName, OutputUserInfo());
Then inside OutputUserInfo() you can have whatever formatting to the data that you want so you can understand what they put in.
Edit Example of OutputUserInfo()
private string OutputUserInfo() {
return "First Name: " + tbFirstName.Text + Environment.NewLine +
"Surname: " + tbSurname.Text + Environment.NewLine +
"Address" + tbAddress.Text + Environment.NewLine;
// Just keep adding whatever you want on here.
// Add the descriptions if you want, it will probably help
}
You could also have this in different formats (CSV, or whatever). But if you're just doing a plain text file, this could be easiest. It is up to you though.
File.WriteAllText is probably bad because it overwrites your content.
Creates a new file, writes the specified string to the file, and then closes the file. If the target file already exists, it is overwritten.
Instead go with File.AppendAllText which
Appends the specified stringto the file, creating the file if it does not already exist.
There we go, use Encoding to Append all the string.
private void button1_Click(object sender, EventArgs e)
{
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string line = string.Format("{0},{1}"
, textBox1.Text
, textBox2.Text);
File.AppendAllText(saveFileDialog1.FileName, line, Encoding.GetEncoding(1252));
}
}

Changing the code behind

I'm supposed to change the frmPersonnelVerified code behind to get the values from the Session state items.
Here is my session state code:
public partial class frmPersonnel : System.Web.UI.Page
{
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
//Checking validation for the text boxes
if (string.IsNullOrEmpty((txtFirstName.Text ?? string.Empty).Trim()))
{
txtFirstName.BackColor = System.Drawing.Color.Yellow;
lblError.Text += "Please enter first name! <br />";
}
if (string.IsNullOrEmpty((txtLastName.Text ?? string.Empty).Trim()))
{
txtLastName.BackColor = System.Drawing.Color.Yellow;
lblError.Text += "Please enter last name! <br />";
}
if (string.IsNullOrEmpty((txtPayRate.Text ?? string.Empty).Trim()))
{
txtPayRate.BackColor = System.Drawing.Color.Yellow;
lblError.Text += "Please enter pay rate! <br />";
}
if (string.IsNullOrEmpty((txtStartDate.Text ?? string.Empty).Trim()))
{
txtStartDate.BackColor = System.Drawing.Color.Yellow;
lblError.Text += "Please enter start date! <br />";
}
if (string.IsNullOrEmpty((txtEndDate.Text ?? string.Empty).Trim()))
{
txtEndDate.BackColor = System.Drawing.Color.Yellow;
lblError.Text += "Please enter end date! <br />";
}
DateTime dt1;
DateTime dt2;
dt1 = DateTime.Parse(txtStartDate.Text);
dt2 = DateTime.Parse(txtEndDate.Text);
if (DateTime.Compare(dt1, dt2) > 0)
{
//Checking if the end date is greater than the start date
txtStartDate.BackColor = System.Drawing.Color.Yellow;
txtEndDate.BackColor = System.Drawing.Color.Yellow;
lblError.Text += "Start Date must not be greater than End Date! <br />";
}
else
{
//output information if correct validation
Session["txtFirstName"] = txtFirstName.Text;
Session["txtLastName"] = txtLastName.Text;
Session["txtPayRate"] = txtPayRate.Text;
Session["txtStartDate"] = txtStartDate.Text;
Session["txtEndDate"] = txtEndDate.Text;
Server.Transfer("frmPersonalVerified.aspx");
}
}
catch (Exception ex)
{
}
}
}
I have a submit button that when pressed is supposed to input the above information into a text box on another page if it validates correctly. Right now it doesn't do that.
Here is my code on frmPersonnalVerified:
public partial class frmPersonnelVerified : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Inputs information from frmPersonnel and places it into the
//textbox called "txtVerifiedInfo"
txtVerifiedInfo.Text = Request["txtFirstName"] +
"\n" + Request["txtLastName"] +
"\n" + Request["txtPayRate"] +
"\n" + Request["txtStartDate"] +
"\n" + Request["txtEndDate"];
}
}
You're storing the variables in Session but then trying to access them through the Request object. Change it to Session, and it should work:
public partial class frmPersonnelVerified : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Inputs information from frmPersonnel and places it into the
//textbox called "txtVerifiedInfo"
txtVerifiedInfo.Text = Session["txtFirstName"] +
"\n" + Session["txtLastName"] +
"\n" + Session["txtPayRate"] +
"\n" + Session["txtStartDate"] +
"\n" + Session["txtEndDate"];
}
}
However, putting values into Session can be problematic so be cautious.
This is the order in which the events are being handled:
Page_Load
btnSubmit_Click
Page_Render
If you move your code from Page_Load to Page_Render it should work.
protected void Page_Render(object sender, EventArgs e)
{
//Inputs information from frmPersonnel and places it into the
//textbox called "txtVerifiedInfo"
txtVerifiedInfo.Text = Request["txtFirstName"] +
"\n" + Request["txtLastName"] +
"\n" + Request["txtPayRate"] +
"\n" + Request["txtStartDate"] +
"\n" + Request["txtEndDate"];
}
In your verified class you're trying to get the values from the request object not the session object.
The Request object will give you accesss to information either posted back (E.g. form fields) or part of the query string and as the name suggest is associated with a specific request. The Session object is associated with the current user session and you can place and retrieve arbitrary objects in that object.
As a side note since this does not seem to have anything to do with your problem.
It's seldom needed to access the Request object in ASP.NET for values relying on ASP.NETs capabilities to construct object graphs based on request data is generally a better solution.
in code this could look like:
public partial class frmPersonnelVerified : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Inputs information from frmPersonnel and places it into the
//textbox called "txtVerifiedInfo"
txtVerifiedInfo.Text = Session["txtFirstName"] +
"\n" + Session["txtLastName"] +
"\n" + Session["txtPayRate"] +
"\n" + Session["txtStartDate"] +
"\n" + Session["txtEndDate"];
}
}

Categories