c# winforms Error provider issue - c#

I am stuck with trying to display two error mssgs for one textbox
1. if textbox empty -mssg please enter value..this works ok for me
2.text box to accept only numeric values
Any help much appreciated
thank you
here is my code: scroll down for actual errorprovider attempt
ListClass lc = new ListClass();
private void btnAddStu_Click(object sender, EventArgs e)
{
string title = cboTitle.SelectedItem.ToString();
string fname = txtFname.Text;
string lname = txtLname.Text;
string dob = dtpDOB.Text;
int stuId = int.Parse(txtSid.Text);
string status = cboStatus.SelectedItem.ToString();
string phone = txtPhone.Text;
string email = txtEmail.Text;
lblRemarks.Text = lc.AddStudent(title, fname, lname, dob, stuId, status, phone, email);
txtEmail.Clear();
txtFname.Clear();
txtLname.Clear();
txtPhone.Clear();
txtSid.Clear();
Errorprovide code:
private void txtSid_Validating(object sender, CancelEventArgs e)
{
bool can = false;
int sid = 0;
if (string.IsNullOrEmpty(txtSid.Text))
{
ep1.SetError(txtSid, "Please Enter Student ID");
can = true;
}
else if (int.TryParse(txtSid.Text, out sid))
{
ep1.SetError(txtSid, "Student ID must be a number");
can = true;
}
e.Cancel = can;
}

Instead of using your event, you should try this
private void textbox_KeyPress(object sender, KeyPressEventArgs e)
{
try
{
if (e.KeyChar == '.' || e.KeyChar == Convert.ToChar(Keys.Back))
{
if (e.KeyChar == '.' && textIIC.Text.Contains('.'))
{
e.Handled = true;
}
return;
}
e.KeyChar = Char.ToUpper(e.KeyChar);
decimal isNumber = 0;
e.Handled = !decimal.TryParse(e.KeyChar.ToString(), out isNumber);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
This code I provide above only allowed you to input number, nothing but number :)

Related

retain previous value of text box till the form is closed

I am very new to c# , and learning to make data entry application,
in my entry form when the user clicks save all the data text boxes are refreshed and saved to database and the text box appears empty to enter gain. This is a continuous process.
Now i want my textbox1 to retain the same value where the user first entered till the form is closed.
Please help me how to achieve this?
i tried this code but the textbox is still empty:
private string value;
private void materiaNumberTextBox_TextChanged(object sender, EventArgs e)
{
var oldValue = value;
value = ((TextBox)sender).Text; // text1.Text
}
here's the code that does while saving:
private void btnsave_Click(object sender, EventArgs e)
{
try
{
String msg = "Confirm Save?";
String caption = "Save Record";
MessageBoxButtons buttons = MessageBoxButtons.YesNo;
MessageBoxIcon ico = MessageBoxIcon.Question;
DialogResult result;
result = MessageBox.Show(this, msg, caption, buttons, ico);
if (result == DialogResult.Yes)
{
generateautoID();
this.iP_SpoolsBindingSource.EndEdit();
MessageBox.Show("The Record saved Successfully:" + outputSpoolNoTextBox.Text, "Save_Update",
MessageBoxButtons.OK, MessageBoxIcon.Information);
this.iP_SpoolsTableAdapter.Update(this.pINQCDataSet.IP_Spools);
this.iP_SpoolsTableAdapter.Fill(this.pINQCDataSet.IP_Spools);
//MessageBox.Show("The Record saved Successfully:", "Save_Update",
//MessageBoxButtons.OK, MessageBoxIcon.Information);
this.iP_SpoolsBindingSource.AddNew();
string strStartenddateformat = "dd-MM-yyyy";
materialTypeComboBox.ValueMember = "Tungsten";
unitComboBox.ValueMember = "Mic";
statusComboBox.ValueMember = "Accepted";
cFComboBox.ValueMember = "";
bowOutOfComboBox.ValueMember = "";
ductilityOutofComboBox.ValueMember = "";
finishUOMComboBox.ValueMember = "Mic";
finishTypeComboBox.ValueMember = "Clean";
rejectReason1ComboBox.ValueMember = "";
rejectReason2ComboBox.ValueMember = "";
rejectReason3ComboBox.ValueMember = "";
lotNoTextBox.Text = "0";
dOEDateTimePicker.Format = DateTimePickerFormat.Custom;
dOEDateTimePicker.CustomFormat = strStartenddateformat;
dOEDateTimePicker.Value = DateTime.Now;
dOPDateTimePicker.Format = DateTimePickerFormat.Custom;
dOPDateTimePicker.CustomFormat = strStartenddateformat;
dOPDateTimePicker.Value = DateTime.Now;
}
else
{
return;
}
}
catch (Exception ex)
{
MessageBox.Show("Saving Failed:" + ex.Message.ToString(), "Save",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
here's the image of my form:
You can try the following code to save the first input text in the textbox.
Please use the event textbox_Leave event.
private void button1_Click(object sender, EventArgs e)
{
//Update the database
MessageBox.Show("Update success");
textBox1.Text = textbox; // return to the first input in the textbox
}
int i = 0;
string textbox = "";
private void textBox1_Leave(object sender, EventArgs e)
{
if (i == 0)
{
textbox = textBox1.Text;
i++;
}
}
Result:
Use a data reader to get the values from database and then populate values in textbox using those values.

How to validate textbox value while user enters and display error message?

So, I have to code for a method that validates whether the string that saves name contains alphabets only, no numbers. The validation of textbox values should apply when the user enters by textchanged event before submitting the form and display an error message of red color on the label. My code works but the problem is when I enter a numeric number in text box, the label displays error which stays even when I delete the text box value and enter the alphabetic string.
I have declared a method which assign error string to label, and is called if regular expression does not match with the text box input, during text changed event.
public void Validator()
{
Calculate_Salary.Enabled = false;
label4.Text = "Please enter only alphabetical letters";
}
private void _Name_TextChanged(object sender, EventArgs e)
{
Regex pattern = new Regex("/^[A-Za-z]+$/");
string name = _Name.Text;
if (pattern.IsMatch(name))
{
Calculate_Salary.Enabled = true;
label4.Text = "";
}
else
{
Validator();
}
}
Just clear the textbox before you validate:
public void Validator()
{
Calculate_Salary.Enabled = false;
label4.Text = "Please enter only alphabetical letters";
}
private void _Name_TextChanged(object sender, EventArgs e)
{
label4.Text = "";
Regex pattern = new Regex("/^[A-Za-z]+$/");
string name = _Name.Text;
if (pattern.IsMatch(name))
{
Calculate_Salary.Enabled = true;
}
else
{
Validator();
}
}
Your Regex comparison is wrong try this code:
public void Validator()
{
Calculate_Salary.Enabled = false;
label4.Text = "Please enter only alphabetical letters";
}
private void _Name_TextChanged(object sender, EventArgs e)
{
label4.Text = "";
string name = _Name.Text;
if (Regex.IsMatch(name, #"^[a-zA-Z]+$"))
Calculate_Salary.Enabled = true;
else
Validator();
}
I changed the validation code. It seems to work now.
private void _Name_TextChanged(object sender, EventArgs e)
{
label4.Text = string.Empty;
string name = _Name.Text;
if (Regex.IsMatch(_Name.Text, "^[a-zA-Z]+$") || _Name.Text=="")
{
Calculate_Salary.Enabled = true;
}
else
{
Calculate_Salary.Enabled = false;
label4.Text = Validator();
}
}

C# winform - equivalent of InputScope

Is there a property in Winform (.Net 4.0) that is equivalent to InputScope in UWP?
No I do not believe so. You need to use the Validating event
Such as if you want to assure the textbox contains an email you would do something like this:
private void textBox1_Validating(object sender,
System.ComponentModel.CancelEventArgs e)
{
string errorMsg;
if(!ValidEmailAddress(textBox1.Text, out errorMsg))
{
// Cancel the event and select the text to be corrected by the user.
e.Cancel = true;
textBox1.Select(0, textBox1.Text.Length);
// Set the ErrorProvider error with the text to display.
this.errorProvider1.SetError(textBox1, errorMsg);
}
}
private void textBox1_Validated(object sender, System.EventArgs e)
{
// If all conditions have been met, clear the ErrorProvider of errors.
errorProvider1.SetError(textBox1, "");
}
public bool ValidEmailAddress(string emailAddress, out string errorMessage)
{
// Confirm that the email address string is not empty.
if(emailAddress.Length == 0)
{
errorMessage = "email address is required.";
return false;
}
// Confirm that there is an "#" and a "." in the email address, and in the correct order.
if(emailAddress.IndexOf("#") > -1)
{
if(emailAddress.IndexOf(".", emailAddress.IndexOf("#") ) > emailAddress.IndexOf("#") )
{
errorMessage = "";
return true;
}
}
errorMessage = "email address must be valid email address format.\n" +
"For example 'someone#example.com' ";
return false;
}

Bind GridView on Button Click Event with Pagination

I'm new to asp.net and needs some help. I have a gridview with paging for every 20 records per page, I have a search button outside the gridview. What I need to do is when I click the search button, the results must be bind to gridview(which is happening now), however when the records are more than the pagesize and I need to go to the next page of the grid, the binding is lost and the binded records are the ones form the page on load event. below is my code sample.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
public void BindData()
{
{
List<EventFile> eventFile = new List<EventFile>();
eventFile = CoMailAssociationDAL.GetUploadFileUnAssigned(0, "", "", "U");
if (gvwAssociation.DataSource == null)
{
gvwAssociation.DataSource = eventFile;
gvwAssociation.DataBind();
}
}
}
protected void btnSearch_Click(object sender, EventArgs e)
{
int uFlag = 0;
string uploadFlag = this.ddlUploadDate.SelectedValue;
string fileName = this.txtSearchText.Text;
string uploadDt = this.txtDate.Text;
string status = this.ddlStatus.SelectedValue.ToString();
bt = true;
if (status == "Un-Assigned")
{
status = "U";
}
else if (status == "Assigned")
{
status = "A";
}
else
{
status = "B";
}
if ((uploadFlag == "On") && (uploadDt == ""))
{
uFlag = 0;
}
else if (uploadFlag == "On")
{
uFlag = 1;
}
else if (uploadFlag == "OnorBefore")
{
uFlag = 2;
}
else
{
uFlag = 3;
}
fileSearch = CoMailAssociationDAL.SearchFile(uFlag, fileName, uploadDt, status);
gvwAssociation.DataSource = fileSearch;
gvwAssociation.DataBind();
}
protected void gvwAssociation_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
//SaveSelectedValues();
gvwAssociation.PageIndex = e.NewPageIndex;
//BindData();
//PopulateSelectedValues();
}
First of all you should have the following event handler for paging
protected void gvwAssociation_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvwAssociation.PageIndex = e.NewPageIndex;
bindGridWithFilter();
}
Then, move your search/ filter logic within the search button to a private method (say "bindGridWithFilter")
TIP: Try to combine both BindData and bindGridWithFilter so when there's no filter you display all records
UPDATE
Here's some refactored code for you to get an idea what I meant above.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindGridWithFilter();
}
}
protected void gvwAssociation_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvwAssociation.PageIndex = e.NewPageIndex;
bindGridWithFilter();
}
protected void btnSearch_Click(object sender, EventArgs e)
{
bindGridWithFilter();
}
private void bindGridWithFilter()
{
List<EventFile> eventFile = new List<EventFile>();
eventFile = CoMailAssociationDAL.GetUploadFileUnAssigned(0, "", "", "U");
if (gvwAssociation.DataSource == null)
{
// If you don't have a filter you show all records
gvwAssociation.DataSource = eventFile;
gvwAssociation.DataBind();
}
else
{
// This is same as the logic in your search button
// display only the filtered records
int uFlag = 0;
string uploadFlag = this.ddlUploadDate.SelectedValue;
string fileName = this.txtSearchText.Text;
string uploadDt = this.txtDate.Text;
string status = this.ddlStatus.SelectedValue.ToString();
bt = true;
if (status == "Un-Assigned")
{
status = "U";
}
else if (status == "Assigned")
{
status = "A";
}
else
{
status = "B";
}
if ((uploadFlag == "On") && (uploadDt == ""))
{
uFlag = 0;
}
else if (uploadFlag == "On")
{
uFlag = 1;
}
else if (uploadFlag == "OnorBefore")
{
uFlag = 2;
}
else
{
uFlag = 3;
}
List<EventFile> fileSearch = CoMailAssociationDAL.SearchFile(uFlag, fileName, uploadDt, status);
gvwAssociation.DataSource = fileSearch;
gvwAssociation.DataBind();
}
}
This should work.

Removing particular items from menu and replacing the new menu through content page in asp.net?

I have a menu and label in my master page which i want to update depending on the type of user logged in.
Firstly am removing few MenuItems from the menu that is working fine but its not showing up in the master page. Instead the old menu is only seen with all the menu items for limited user also. When i debug the label text shows what i have set but when page loads its not updating too.
Am using the following code.
Label lbWelcomeMessage = new Label();
protected void Page_Load(object sender, EventArgs e)
{
Master.FindControl("CAMenu").Visible = false;
}
protected void btnLogin_Click(object sender, EventArgs e)
{
string userName = txtUsername.Text;
string password = txtPassword.Text;
Common common = new Common();
DataTable tab = new DataTable();
tab= common.GetUserDetails(userName);
string firstName = string.Empty;
string userPassword = string.Empty;
string RoleID=string.Empty;
if (tab.Rows.Count == 1)
{
firstName = tab.Rows[0][2].ToString();
userPassword = tab.Rows[0][4].ToString();
RoleID = tab.Rows[0][5].ToString();
}
if (userPassword == password)
{
if (RoleID != "1")
{
Menu CAMenu = new Menu();
CAMenu = (Menu)Master.FindControl("CAMenu");
int count = CAMenu.Items.Count;
for (int i = 3; i > 0; i--)
{
string text = CAMenu.Items[i - 1].Text;
CAMenu.Items.RemoveAt(i - 1);
}
lbWelcomeMessage = (Label)Master.FindControl("lbLoginMessage");
lbWelcomeMessage.Text = "Welcome"+" "+ firstName;
((SiteMaster)Page.Master).MyText = lbWelcomeMessage.Text;
Response.Redirect("AdHocSMS.aspx");
}
else
{
lbWelcomeMessage = (Label)Master.FindControl("lbLoginMessage");
lbWelcomeMessage.Text = lbWelcomeMessage.Text+" "+firstName ;
Response.Redirect("NewTemplate.aspx");
}
}
}
I assume you have written this code in your login.aspx. When login button is clicked then it takes you to another page and all the life cycle of page is run again. and master page contents are reset.
The solution to this problem could be. Move this logic to your master page code like
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (Session.Count == 0 || Session["Username"] == null)
Response.Redirect("~/Login.aspx", true);
CheckRole();
}
public void CheckRole()
{
if (System.Web.HttpContext.Current.Session.Count > 0)
{
tab= common.GetUserDetails(Session["Username"]);
if (tab.Rows.Count == 1)
{
firstName = tab.Rows[0][2].ToString();
userPassword = tab.Rows[0][4].ToString();
RoleID = tab.Rows[0][5].ToString();
}
if (RoleID != "1")
{
Menu CAMenu = new Menu();
int count = CAMenu.Items.Count;
for (int i = 3; i > 0; i--)
{
string text = CAMenu.Items[i - 1].Text;
CAMenu.Items.RemoveAt(i - 1);
}
//your label logic
lbWelcomeMessage.Text = "Welcome"+" "+ firstName;
((SiteMaster)Page.Master).MyText = lbWelcomeMessage.Text;
Response.Redirect("AdHocSMS.aspx");
}
else
{
//Logic
Response.Redirect("NewTemplate.aspx");
}
}
else
{
Session.Abandon();
Response.Redirect("~/Login.aspx", true);
}
}
You have to put a UserId or Username in Session this is the one disadvantage but for every page you dont have to worry about anything.
for life cycle read this article http://msdn.microsoft.com/en-us/library/ms178472.aspx
let me know if it solves or not.
What i did is something like this
In Site.Mater:-
public void CheckRole()
{
try
{
if (System.Web.HttpContext.Current.Session.Count > 0)
{
string firstName = string.Empty;
// string userPassword = string.Empty;
string RoleID = string.Empty;
Common common = new Common();
DataTable tab = new DataTable();
string userName = (string)Session["UserName"];
User user = new User(userName);
tab = user.GetUserDetails(userName);
if (tab.Rows.Count == 1)
{
firstName = tab.Rows[0][1].ToString();
RoleID = tab.Rows[0][3].ToString();
}
if (RoleID != "1")
{
int count = CAMenu.Items.Count;
if (count == 5)
{
for (int menuCount = 3; menuCount > 0; menuCount--)
{
string text = CAMenu.Items[menuCount - 1].Text;
CAMenu.Items.RemoveAt(menuCount - 1);
}
}
lbLoginMessage.Text = "Welcome," + " " + firstName;
loginStatus.Visible = true;
}
else
{
lbLoginMessage.Text = "Welcome," + " " + firstName;
loginStatus.Visible = true;
}
}
else
{
Session.Abandon();
Response.Redirect("~/Login.aspx", true);
}
}
catch (Exception ex)
{
new Logger().Log("ShortCom.SiteMaster.CheckRole()", ex.Message);
Response.Redirect("~/Error.aspx");
}
}
In Login.Apsx:-
protected void Page_Load(object sender, EventArgs e)
{
try
{
Master.FindControl("CAMenu").Visible = false;
Master.FindControl("loginStatus").Visible = false;
}
catch (Exception ex)
{
new Logger().Log("ShortCom.Login.btnLogin_Click(object sender, EventArgs e)", ex.Message);
Response.Redirect("~/Error.aspx");
}
}
protected void LoadMessageBox(string MessageID)
{
try
{
messages = new GUIMessages();
popupExtend = new ModalPopupExtender();
lbMessage = (Label)Master.FindControl("label5");
lbMessage.Text = messages.GetGUIMessage(GUIModule.Login, MessageID);
popupExtend = (ModalPopupExtender)Master.FindControl("popupExtender");
popupExtend.Show();
}
catch (Exception ex)
{
new Logger().Log("ShortCom.Login.LoadMessageBox(string MessageID)", ex.Message);
Response.Redirect("~/Error.aspx");
}
}
protected void btnLogin_Click(object sender, EventArgs e)
{
try
{
string userName = txtUsername.Text;
string password = txtPassword.Text;
if (userName == string.Empty && password == string.Empty)
{
LoadMessageBox("5");
txtUsername.Focus();
return;
}
if (userName == string.Empty)
{
LoadMessageBox("1");
txtUsername.Focus();
return;
}
else if (password == string.Empty)
{
LoadMessageBox("3");
txtPassword.Focus();
return;
}
User user = new User(userName);
DataTable tab = new DataTable();
tab = user.GetUserDetails(userName);
string firstName = string.Empty;
string userPassword = string.Empty;
string RoleID = string.Empty;
string userID = string.Empty;
Session["UserName"] = userName;
if (tab.Rows.Count == 0)
{
LoadMessageBox("6");
txtPassword.Text = string.Empty;
txtUsername.Text = string.Empty;
txtUsername.Focus();
return;
}
if (tab.Rows.Count == 1)
{
userID = tab.Rows[0][0].ToString();
firstName = tab.Rows[0][1].ToString();
userPassword = tab.Rows[0][2].ToString();
RoleID = tab.Rows[0][3].ToString();
Session["UserID"] = userID;
}
//if (firstName != userName)
//{
// LoadMessageBox("2");
// txtUsername.Focus();
// return;
//}
//else
{
if (userPassword == password)
{
Response.Redirect("~/Default.aspx");
}
else
{
LoadMessageBox("4");
txtPassword.Focus();
return;
}
}
}
catch (Exception ex)
{
new Logger().Log("ShortCom.Login.btnLogin_Click(object sender, EventArgs e)", ex.Message);
Response.Redirect("~/Error.aspx");
}
}

Categories