Implement check availability functionality on save button - c#

I have created a link button in aspx form which check availablity of login email address and its functionality is as.
protected void lnkCheckAvailable_Click(object sender, EventArgs e)
{
SystemUserBL bl = new SystemUserBL(SessionContext.SystemUser);
ds = new DataSet();
bl.FetchForLoginEmailAddress(ds, txtLoginEmailAddress.Text);
if (ds.Tables[0].Rows.Count > 0)
{
valDuplicatePassword.Visible = true;
valDuplicatePassword.Text = "<b>This User Name is already in use by another user.</b>";
}
else
{
valDuplicatePassword.Visible = true;
valDuplicatePassword.Text = "<b>Congratulations! " + txtLoginEmailAddress.Text + " is available.</b>";
}
}
It's working fine when user will click on check availability link button. There is another button "Save" which saves the user information in the table. Now my issue is that if it displays "This User Name is already in use by another user." message the information is still saved in the database. Please tell me how to prevent this!!!

You can return true or false based on user name exists in database or not. You can create a method which will check user availability.
When user press save button you will call that method if method returns true it means user exists.
private bool CheckUserAvailability()
{
SystemUserBL bl = new SystemUserBL(SessionContext.SystemUser);
ds = new DataSet();
bl.FetchForLoginEmailAddress(ds, txtLoginEmailAddress.Text);
if (ds.Tables[0].Rows.Count > 0)
{
valDuplicatePassword.Visible = true;
valDuplicatePassword.Text = "<b>This User Name is already in use by another user.</b>";
return true;
}
else
{
valDuplicatePassword.Visible = true;
valDuplicatePassword.Text = "<b>Congratulations! " + txtLoginEmailAddress.Text + " is available.</b>";
return false;
}
}
You can also call this method on link click.
protected void lnkCheckAvailable_Click(object sender, EventArgs e)
{
CheckUserAvailability();
}
You will call this method on Save button if user don't exist than save information in database.
protected void Savebtn_Click(object sender, EventArgs e)
{
if(CheckUserAvailability() == false)
{
SaveUserInfoToDataBase();
}
}

Related

DataGridView not loading data programmatically

I am working on a Windows application where I get an input from a TextBox and add it to the DataGridView when user clicks on a Button (Add).
My problem is that when I add the text for the first time, it works fine and its added to the grid.
When I add new text, it's not added to the DataGridView. Once the Form is closed and reopened with the same object then I am able to see it.
Code:
private void btnAddInput_Click(object sender, EventArgs e)
{
if (Data == null)
Data = new List<Inputs>();
if (!string.IsNullOrWhiteSpace(txtInput.Text))
{
Data.Insert(Data.Count, new Inputs()
{
Name = txtInput.Text,
Value = string.Empty
});
}
else
{
MessageBox.Show("Please enter parameter value", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
txtInput.Text = "";
gridViewInputs.DataSource = Data;
}
I am not sure what is causing the record not to be added to grid on second add button click.
You could set the DataGridView.DataSource to null before setting a new one.
This would cause the DataGridView to refresh its content with the new data in the source List<Inputs>:
the underlying DataGridViewDataConnection is reset only when the DataSource reference is different from the current or is set to null.
Note that when you reset the DataSource, the RowsRemoved event is raised multiple times (once for each row removed).
I suggest to change the List to a BindingList, because any change to the List will be reflected automatically and because it will allow to remove rows from the DataGridView if/when required: using a List<T> as DataSource will not allow to remove a row.
BindingList<Inputs> InputData = new BindingList<Inputs>();
You can always set the AllowUserToDeleteRows and AllowUserToAddRows properties to false if you don't want your Users to tamper with the grid content.
For example:
public class Inputs
{
public string Name { get; set; }
public string Value { get; set; }
}
internal BindingList<Inputs> InputData = new BindingList<Inputs>();
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.DataSource = InputData;
}
private void btnAddInput_Click(object sender, EventArgs e)
{
string textValue = txtInput.Text.Trim();
if (!string.IsNullOrEmpty(textValue))
{
InputData.Add(new Inputs() {
Name = textValue,
Value = "[Whatever this is]"
});
txtInput.Text = "";
}
else
{
MessageBox.Show("Not a valid value");
}
}
If you want to keep using a List<T>, add the code required to reset the DataGridView.DataSource:
private void btnAddInput_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textValue))
{
//(...)
dataGridView1.DataSource = null;
dataGridView1.DataSource = InputData;
txtInput.Text = "";
}
//(...)

C# PostBack Issue

I'm having some issues with posting back a RowCommand from a GridView. Not sure if my logic is correct so if somebody could point out where I am going wrong that would be great.
It seems there are lot of similar problems but none of the solutions have a default set of results in the gridview then rebinded with search results like this scenario.
The problem is when the RowCommand is fired I have the wrong result. On default load the button works correctly but if I search for customers and then use the RowCommand, the page posts back and rebinds the grid with the default customers always sending me to the wrong customer.
Page Load: Fill GridView with logged in users default clients
Search Box: Search companies entire client list and repopulate gridview
RowCommand: Send users to the customer
Postback:
if(!IsPostBack)
{
//Check if user logged in
User A_User = new User();
if(!A_User.Check_Logged_In())
{
if(A_User.Should_Redirect(System.IO.Path.GetFileName(Request.PhysicalPath)))
{
//Redirect user to login page
Response.Redirect(A_User.Login_Page());
}
}
//Modify nav buttons
HtmlGenericControl nav = (HtmlGenericControl)this.Page.Master.FindControl("UserPanel").FindControl("li_nav_address_book");
nav.Attributes["class"] = "active";
//Load logged in users customers
BindGrid(false);
}else
{
//Check for request
if(Request.Params["__EVENTTARGET"] != null)
{
//Check for search string
if(Request.Params["__EVENTTARGET"].ToString().Contains("SearchCustomers"))
{
//Load customers by search results
BindGrid(true);
}
//else
//{
// if(Request.Params["__EVENTTARGET"].ToString().Contains("btn2"))
// {
// Console.WriteLine("SENDER: ", "btn2 RowCommand");
// BindGrid(true);
// }
//}
}
}
Search Button:
protected void btn_Search_Click(object sender, EventArgs e)
{
BindGrid(true);
}
Grid Binding:
private void BindGrid(bool Search)
{
if(!Search)
{
//Load customers by rep ID
Contacts Contact_Manager = new Contacts();
gvCustomers.DataSource = null;
DataSet dsCustomers = Contact_Manager.Get_Customers_By_UserID((int)Session["User_ID"]);
DataTable tblCustomers = dsCustomers.Tables[0];
gvCustomers.DataSource = tblCustomers;
gvCustomers.DataBind();
}
else
{
//Load customers by search terms
Contacts Contact_Manager = new Contacts();
//Search by replacing spaces to do a rainbow database search as whole text instead of tags
DataSet dsCustomers = Contact_Manager.Get_Customers_By_Tags(tb_GetContacts.Text.Replace(" ", ""));
DataTable tblCustomers = dsCustomers.Tables[0];
gvCustomers.DataSource = null;
gvCustomers.DataSource = tblCustomers;
gvCustomers.DataBind();
}
}
RowCommand:
protected void gvCustomers_RowCommand(object sender,
GridViewCommandEventArgs e)
{
if(e.CommandName == "Customer_Detail")
{
int Customer_ID = Convert.ToInt32(e.CommandArgument);
Response.Redirect("~/Customer/" + Customer_ID);
}
}

Populating textBoxes with

I'm designing a CheckOut page and I want to automatically load the signed in user's information with data from the database using linq. I'm using a method FillPage which I call in PageLoad and so far it looks like this:
void FillPage(int id)
{
using (DatabaseContext db=new DatabaseContext()
{
var query = (from user in db.[tblUser]
where user.ID == id
select user
).First();
if (query != null)
{
txtName.Text = query.Username;
txtEmail.Text = query.Email;
txtAddress.Text = query.PostalAddress;
ddProvice.SelectedValue = query.Province;
lblPassword.Text = query.Password;
lblDate.Text = query.DateRegistered.ToString();
}
}
}
Why does nothing happen when I load the page?
You must insert more of your code .your problem is not clear
May be in your load event of your page you forget to add
If (! IsPostback)
{
}
And may be you have reset your fields
public void MyPage_load( object sender , EventArgs e)
{
//Reset fields
}
This will fix your problem
public void MyPage_load( object sender , EventArgs e)
{
If (! IsPostback)
{
//Reset fields
}
}

Enabled the button after the form opened c#

currently my window is like this with the edit and delete button disabled. In order to enable the buttons, user have to login with the administrator type. Right now, I already login with the administrator type from the member type. The disabled buttons supposed to be enabled after I logged in with the administrator type, but it is not.
Is there any way to enable the button, after the form opened with the buttons disabled?
Here is the images:
As you can see on the below image, there is a admin login button with edit and delete buttons disabled. (Main System Form):
Administrator Login (Privelege Form)
Here is the code that I am using:
public class SystemManager
{
public static void AdminLogin(string _value1, string _value2, Form _windowsForm, TextBox _windowsTextBox)
{
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
string query = "SELECT * FROM [Member] WHERE [Username] = #Username";
connection.Open();
using (OleDbCommand command = new OleDbCommand(query, connection))
{
command.Parameters.Add("#Username", OleDbType.VarChar);
command.Parameters["#Username"].Value = _value1;
using (OleDbDataReader reader = command.ExecuteReader())
{
if (reader.Read())
{
string password = (string)reader["Password"];
string userType = (string)reader["UserType"];
_isValidPassword = BCrypt.ValidateHash(_value2, password);
if (userType == "Administrator")
{
_isAdministrator = true;
}
else if (userType != "Administrator")
{
_isAdministrator = false;
}
if (_isValidPassword && _isAdministrator)
{
Authenticate _authenticate = new Authenticate();
_authenticate.ShowDialog();
ShowMessageBox("Authenticated.", "Success", 2);
UserInformation.isAdministrator = true;
_windowsForm.Hide();
_windowsForm.Close();
}
}
if (!_isValidPassword || !_isAdministrator)
{
Authenticate _authenticate = new Authenticate();
_authenticate.ShowDialog();
ShowMessageBox("Either username or password incorrect or you are not administrator. Please try again.", "Error", 1);
ClearTextBoxes(_windowsForm.Controls);
_windowsTextBox.Focus();
}
reader.Close();
}
}
connection.Close();
}
}
}
public partial class MainSystem: Form
{
void MainSystem_Load(object sender, EventArgs e)
{
UserPrivelege();
}
void UserPrivelege()
{
if (UserInformation.CurrentLoggedInUserType == "Member")
{
this.button3.Enabled = false; // Edit Button
this.button4.Enabled = false; // Delete Button
this.button7.Enabled = false;
this.button9.Enabled = true; // Admin Login Button
}
else if (UserInformation.CurrentLoggedInUserType == "Administrator" || UserInformation.isAdministrator)
{
this.button3.Enabled = true; // Edit Button
this.button4.Enabled = true; // Delete Button
this.button7.Enabled = true;
this.button9.Enabled = false; // Admin Login Button
}
}
}
public partial class Privelege : Form
{
void button1_Click(object sender, EventArgs e) // OK Button
{
Check();
}
void Check()
{
if (this.textBox1.Text == string.Empty || string.IsNullOrWhiteSpace(this.textBox1.Text))
{
SystemManager.ShowMessageBox("Username field required.", "Information", 2);
}
else if (this.textBox2.Text == string.Empty || string.IsNullOrWhiteSpace(this.textBox2.Text))
{
SystemManager.ShowMessageBox("Password field required.", "Information", 2);
}
else
{
SystemManager.AdminLogin(this.textBox1.Text, this.textBox2.Text, this, this.textBox1);
}
}
Thank you.
I really appreciate your answer.
There are several architectural issues here which when resolved will also make this function the way you want. First of all it is not ideal to call a function from a form which will act upon that form. It is a much better practice to return what is needed from that function and have the code to digest that result in the form which it affects. Let's try a simple example of what the login button could do:
private void btnLogin_Click(object sender, EventArgs e)
{
var login = new LoginForm();
login.ShowDialog();
var result = login.DialogResult == System.Windows.Forms.DialogResult.Yes;
if (result)
{
button2.Enabled = true;
button3.Enabled = true;
}
}
Obviously the only way this would work is if your login for was setting its DialogResult property, which is a simple way to pass a result from a modal dialog. We still have the issue of converting a login result to that value. This can be addressed in the login button of the dialog, and the login method it calls.
private void btnDialogLogin_Click(object sender, EventArgs e)
{
// Form validation here...
var result = SystemManager.AdminLogin(NameButton.Text, PassButton.Text);
DialogResult = DialogResult.No;
if (result)
{
DialogResult = DialogResult.Yes;
}
this.Close();
}
Now we have to change the AdminLogin method to a boolean:
public class SystemManager
{
public static bool AdminLogin(string _value1, string _value2)
{
// Database and evluation...
if(isAdmin)
{
return true;
}
return false;
}
}
This will make it easy to pass values as they are needed, without each object knowing more details about the other than is necessary. If the admin login needs to pass more information than just if the user is an admin, than create a class which contains all the different things one might want to know about the user's login and pass that as a return instead.
what you can do here is, once the user clicks login on your first form, you can send a boolean value to the constructor of your second form, say true for admin and false for others and depending on this value you can enable or disable your button.
The form load event, MainSystem_Load(), is only fired once (at first initialization). The UserPrivelege() function isn't called after the admin login. You will need to invoke that functionality after the admin logs in.
assign value to UserInformation.CurrentLoggedInUserType and on click of Admin login button open your login form as dialog and after close of this form call UserPrivelege(); fuction
Admin login onclick :-
PrivelegeForm frm= new LoginForm();
DialogResult result= frm.ShowDialog();
if (result==DialogResult.Ok)
{
UserPrivelege();
}
don't forget to assign your static variable UserInformation.CurrentLoggedInUserType

cannot get datagridview to refresh data

I have the following button click event:
private void button_GetTrucks_Click(object sender, EventArgs e)
{
if (textBox_CompanyCode.Text.Length != 3)
{
_errorProvider.SetError(button_GetTrucks, "Invalid company code.");
return;
}
textBox_CompanyCode.Enabled = false;
button_GetTrucks.Enabled = false;
_corporationId = GetCorporationId(textBox_CompanyCode.Text);
if(_corporationId == Guid.Empty)
{
_errorProvider.SetError(button_GetTrucks, "Could not find company.");
return;
}
dataGridView1.DataSource = null;
_soureItemCollection = null;
textBox_CorporationId.Text = _corporationId.ToString();
var query = GetTrucks(_corporationId);
_soureItemCollection = new ObservableCollection<Truck>(query);
dataGridView1.DataSource = _soureItemCollection;
MakeDataGridViewPerty();
button_GetTrucks.Enabled = true;
textBox_CompanyCode.Enabled = true;
}
public static List<Truck> GetTrucks(Guid corporationId)
{
return (from trk in Entity.Trucks
where trk.CorporationId == corporationId
orderby trk.TruckNumber
select trk).ToList();
}
When I get the data initially by clicking the button, it works fine. If the data has changed, due to another program changing the data and I click this button again to refresh the data, it stays the same and does not display the changed data.
If I restart the application, click the button, the new data is displayed correctly.
So, it takes me restarting the application to reload the data.
Why is the button click not reloading the data?
I have seen where you have to add in a databind to get it to rebind
dataGridView1.DataSource = _soureItemCollection;
dataGridView1.Databind();
Before this call: var query = GetTrucks(_corporationId); place this one first:
Entity.Refresh(RefreshMode.OverwriteCurrentValues,Entity.Trucks);

Categories