C# PostBack Issue - c#

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);
}
}

Related

Implement check availability functionality on save button

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();
}
}

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
}
}

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);

How to Set unique IDs to DataRepeater Link Labels

It is a Windows Form Application in C#.
I am using DataRepeater Control in which I am displaying three columns:
Text Label,Link Label,Link Label
Following is the screenshot:
Following is the code which populates DataRepeater:
private void Get_StaffLogins_RequestList()
{
mySqlConnection = DBAccess.getConnection();
mySqlConnection.Open();
DataTable dt = sysadmin.getStaffLoginsRequests(mySqlConnection);
BindingSource bSource = new BindingSource();
staff_id.DataBindings.Add("Text", bSource, "staff_id");
//accessLink.DataBindings.Add("Value", bSource, "staff_id");
//denyLink.DataBindings.Add("Value", bSource, "staff_id");
if (dt.Rows.Count > 0)
{
bSource.DataSource = dt;
r_msgs.DataSource = bSource;
}
else
{
r_msgs.DataSource = String.Empty;
notify.Text = "There are no Pending requests for staff logins!";
}
mySqlConnection.Close();
}
private void accessLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
//Access Link Clicked
}
private void denyLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
//Deny Link Clicked
}
Now what I need is that when User clicks on Access or Deny Link I somehow get corresponding StaffID so that I can mark that particular staffID Access/Denied in Database.
How can I attribute each Row Link Labels with unique staff ids?
thanks in advance!
I resolved this issue by getting Current Item Index of DataRepeater:
private void accessLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
//Access Link Clicked
int RequestNumber = r_msgs.CurrentItemIndex;
MessageBox.Show(RequestNumber.toString()+1);
//Remaining Code
}
This code Prints the Row number of the Access Link Label, and that's what I wanted!

Add a row to existing databound datagridview

In my Windows application I had a job code combobox and when user selects a jobcode from the combobox it will get the corresponding data from database and will display it in a datagridview below the combobox. All is fine and I am able to load data corresponding to selected jobcode.
I used the this code
public void loadcompljobcodecombobox()
{
completedcobcodeadapterTableAdapter cmpltjbcd = new completedcobcodeadapterTableAdapter();
cmpltjbcd.Connection = new OleDbConnection(Program.ConnStr);
DataTable dt= cmpltjbcd.GetData(int.Parse(cmbcutcode.SelectedValue.ToString()));
if (dt.Rows.Count > 0)
{
cmbjobcode.ValueMember = "jobpk";
cmbjobcode.DisplayMember = "jobcode";
txtcompanyname.Text = "companyname";
cmbjobcode.DataSource = dt;
}
else
{
MessageBox.Show("NO JobCode to be invoiced");
}
}
private void cmbjobcode_SelectedValueChanged(object sender, EventArgs e)
{
tbltoinvoicedtableTableAdapter tbltoinvce = new tbltoinvoicedtableTableAdapter();
tbltoinvce.Connection = new OleDbConnection(Program.ConnStr);
if (cmbjobcode.SelectedValue != null)
{
DataTable dt = tbltoinvce.GetDataBy(int.Parse(cmbjobcode.SelectedValue.ToString()));
dataGridView1.DataSource = dt;
}
}
Now my requirement is user must be able to select more than one jobcode details at a time for invoicing i.e. if he selects one value from jobcode corresponding data should be added in datagridview and when he select another jobcode its corresponding data should be added as next row in the Datagridview.
I had tried very much and find no way can anyone suggest an idea or example
If I understand you correctly, I would try something like this. This isn't tested but it's an idea.
At Form Level:
private BindingList<DataRow> jobList;
Then to add to your current code...
private void cmbjobcode_SelectedValueChanged(object sender, EventArgs e)
{
tbltoinvoicedtableTableAdapter tbltoinvce = new tbltoinvoicedtableTableAdapter();
tbltoinvce.Connection = new OleDbConnection(Program.ConnStr);
if (cmbjobcode.SelectedValue != null)
{
DataRow job = tbltoinvce.GetDataBy(int.Parse(cmbjobcode.SelectedValue.ToString())).Rows[0];
if (jobList == null)
{
jobList = new BindingList<DataRow>();
jobList.Add(job);
dataGridView1.DataSource = jobList;
}
else
{
if (!jobList.Contains(job));
jobList.Add(job);
}
}
}
**Edit: This is assuming your job data contains only one row of data since your question asked for how to add "a row".

Categories