Firefox is causing a few problems for me at the moment and I can't quite figure them out.
I have two listboxes, one is populated when the page is loaded, and the other when an item from the first is selected then click view button. The problem I am having is the 2nd listbox populates for just a split second and then everything is deleted. The function works in all other browsers I have tested.. IE, Chrome, and Safari..
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Data;
using System.Data.SqlClient;
using DAL;
namespace ACESAdmin2.AcesSetup
{
public partial class storefront : System.Web.UI.Page
{
private string selectedCustomer
{
get { return Session["selectedCustomer"] != null ? (string)Session["selectedCustomer"] : string.Empty; }
set { Session["selectedCustomer"] = value; }
}
private string selectedCatalog
{
get { return Session["selectedCatalog"] != null ? (string)Session["selectedCatalog"] : string.Empty; }
set { Session["selectedCatalog"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadPage();
}
}
private void LoadPage()
{
initControls();
#region role setting
try
{
//check user role to determine editing rights
string usersRole = Roles.GetRolesForUser(Membership.GetUser().UserName)[0];
MembershipUser user = Membership.GetUser();
switch (usersRole)
{
case "BasicUser":
AlignTextNoneRadio.Enabled = false;
AlignTextLeftRadio.Enabled = false;
AlignRightRadio.Enabled = false;
AlignCenterRadio.Enabled = false;
headerText.Enabled = false;
returnPolicy.Enabled = false;
welcomeMessageTextBox.Enabled = false;
homeText.Enabled = false;
homeLink.Enabled = false;
updateStoreButton.Enabled = false;
break;
case "Customer":
homeLink.Enabled = false;
homeText.Enabled = false;
break;
case "SalesRep":
case "Admin":
case "SuperAdmin":
break;
default:
break;
}
}
catch (NullReferenceException error)
{
string message;
message = error.ToString();
Response.Redirect("../error.aspx");
}
#endregion
#region Accordion Pane Settings
if (ViewState["SelectedAccordionIndex"] == null)
{
MyAccordion.SelectedIndex = -1;
}
else
{
MyAccordion.SelectedIndex = (int)ViewState["SelectedAccordionIndex"];
}
#endregion
}
private void initControls()
{
//Viewable to all
#region customer label
if (selectedCustomer != null)
{
string customerName = DAL.Util.getCustomerName().ToString();
if (customerName != null || customerName != String.Empty)
{
lblCustomer.Text = "Customer: <font color=maroon>" + customerName + "</font>";
lblCustomer.Visible = true;
}
else
{
lblCustomer.Text = "Customer: <font color=maroon>" + selectedCustomer.ToString() + "</font>";
lblCustomer.Visible = true;
}
}
#endregion
//Edit Store Front
#region Populate Fields
#region headerAlign
string headerAlign = DAL.Util.getHeaderAlign().ToString();
switch (headerAlign)
{
case "left":
AlignTextLeftRadio.Checked = true;
break;
case "center":
AlignCenterRadio.Checked = true;
break;
case "right":
AlignRightRadio.Checked = true;
break;
default:
AlignTextNoneRadio.Checked = true;
break;
}
#endregion
welcomeMessageTextBox.Text = DAL.Util.getWelcome().ToString();
headerText.Text = DAL.Util.getHeaderText().ToString();
returnPolicy.Text = DAL.Util.getReturn().ToString();
homeLink.Text = DAL.Util.getHomeLink().ToString();
homeText.Text = DAL.Util.getHomeText().ToString();
#endregion
//BJIT Setup
#region popultae fields
ddlSelectVendor.DataSource = DAL.Util.getVendors();
ddlSelectVendor.DataBind();
listCatalogs.DataSource = DAL.Util.getCatalogs();
listCatalogs.DataBind();
#endregion
}
protected void returnButton_Click(object sender, EventArgs e)
{
//Takes user back to main admin page
Response.Redirect("../Admin/mainAdmin.aspx");
}
protected void dropdownlist_SelectedInexChange(object sender, EventArgs e)
{
ViewState["SelectedAccordionIndex"] = MyAccordion.SelectedIndex;
}
protected void updateStoreButton_Click(object sender, EventArgs e)
{
switch(MyAccordion.SelectedIndex)
{
case 0:
#region Header Value
string selectedHeaderAlign = null;
foreach (Control control in this.RadioPanel.Controls)
{
if (control is RadioButton)
{
RadioButton radio = control as RadioButton;
if (radio.Checked)
{
selectedHeaderAlign = radio.Text.ToLower();
}
}
}
#endregion
//updates customer information in the table
string sqlSf = "Update Store SET HeaderAlign = #HeaderAlign, HeaderText=#HeaderText, ReturnPolicy=#ReturnPolicy, WelcomeMessage=#WelcomeMessage, HomeTextLink=#HomeTextLink, HomeLink=#HomeLink"
+ " WHERE CustomerID='" + HttpContext.Current.Session["selectedCustomer"].ToString() + "'";
//setting parameters
#region Parameter Values
AdoUtil.ACESSQLParameterCollection parameters = new AdoUtil.ACESSQLParameterCollection();
AdoUtil.ACESSQLParameter param = new AdoUtil.ACESSQLParameter();
param.ParamName = "#HeaderAlign";
param.ParamValue = selectedHeaderAlign.ToString();
param.ParamDBType = SqlDbType.VarChar;
parameters.Add(param);
param = new AdoUtil.ACESSQLParameter();
param.ParamName = "#HeaderText";
param.ParamValue = headerText.Text.ToString();
param.ParamDBType = SqlDbType.VarChar;
parameters.Add(param);
param = new AdoUtil.ACESSQLParameter();
param.ParamName = "#ReturnPolicy";
param.ParamValue = returnPolicy.Text.ToString();
param.ParamDBType = SqlDbType.VarChar;
parameters.Add(param);
param = new AdoUtil.ACESSQLParameter();
param.ParamName = "#WelcomeMessage";
param.ParamValue = welcomeMessageTextBox.Text.ToString();
param.ParamDBType = SqlDbType.VarChar;
parameters.Add(param);
param = new AdoUtil.ACESSQLParameter();
param.ParamName = "#HomeTextLink";
param.ParamValue = homeText.Text.ToString();
param.ParamDBType = SqlDbType.VarChar;
parameters.Add(param);
param = new AdoUtil.ACESSQLParameter();
param.ParamName = "#HomeLink";
param.ParamValue = homeLink.Text.ToString();
param.ParamDBType = SqlDbType.VarChar;
parameters.Add(param);
#endregion
AdoUtil.ExecuteNonQuery(sqlSf, parameters);
break;
case 1:
//BJIT Updates
string sqlBJIT = "Update";
break;
default:
break;
}
MyAccordion.SelectedIndex = -1;
}
#region BJIT Control Events
//BJIT Button
protected void btnAddCustomer_Click(object sender, EventArgs e)
{
if (listItems.SelectedIndex != -1)
{
ArrayList removeArr = new ArrayList();
listItemProfiles.SelectedIndex = -1;
//Copy selected items to listItemProfiles
foreach (ListItem li in listItems.Items)
{
if (li.Selected)
{
listItemProfiles.Items.Add(li);
removeArr.Add(li);
}
}
//Remove the selected items from listItems
foreach (ListItem li in removeArr)
{
listItems.Items.Remove(li);
}
Util.WebFunctions.SortListBox(listItemProfiles);
}
}
//BJIT Button
protected void btnRemoveCustomer_Click(object sender, EventArgs e)
{
if (listItemProfiles.SelectedIndex != -1)
{
ArrayList removeArr = new ArrayList();
listItems.SelectedIndex = -1;
//Copy selected items to listItems
foreach (ListItem li in listItemProfiles.Items)
{
if (li.Selected)
{
li.Selected = false;
listItems.Items.Add(li);
removeArr.Add(li);
}
}
//Remove the selected items from listItemProfiles
foreach (ListItem li in removeArr)
{
listItemProfiles.Items.Remove(li);
}
Util.WebFunctions.SortListBox(listItems);
}
}
//BJIT Button
protected void viewBtn_Click(object sender, EventArgs e)
{
if (listCatalogs.SelectedItem != null)
{
listItemCatalogs.DataSource = DAL.Util.getCatalogProfile(listCatalogs.SelectedValue.ToString());
listItemCatalogs.DataBind();
}
}
//BJIT Button
protected void editBtn_Click(object sender, EventArgs e)
{
if (listCatalogs.SelectedItem != null)
{
#region controls visible
lblVendor.Visible = true;
ddlSelectVendor.Visible = true;
lblItemProfile.Visible = true;
lblItems.Visible = true;
listItems.Visible = true;
listItemProfiles.Visible = true;
btnAddCustomer.Visible = true;
btnRemoveCustomer.Visible = true;
lblItemsCatalog.Visible = false;
listItemCatalogs.Visible = false;
//listItemCatalogs.Items.Clear();
#endregion
#region disable controls
//listCatalogs.Enabled = false;
listItemCatalogs.Enabled = false;
editBtn.Enabled = false;
viewBtn.Enabled = false;
#endregion
listItemProfiles.DataSource = DAL.Util.getCatalogProfile(listCatalogs.SelectedValue.ToString());
listItemProfiles.DataBind();
}
}
//BJIT Drop Down List
protected void ddlSelectVendor_Changed(object sender, EventArgs e)
{
listItems.DataSource = DAL.Util.getVenorItems(ddlSelectVendor.SelectedItem.ToString());
listItems.DataBind();
}
#endregion
}
}
With this there is a little more functionality that was not described previously and with this Firefox also does not keep the data / keep the controls visible when the editBtn_Click is initiated.
And again if there is anything i can clear up I will do my best to reword or anything.
Thank you.
I don't exactly know what happened, but it is working now. I rebuilt the .cs page and recompiled the whole site and everything works. Also cleared the cache of all browsers..
Related
i have this sets of code with setsession and getsession in it
protected void btnCall_Click(Object sender, EventArgs e)
{
if (isCallComplete())
{
Collection<Greeting> collGreeting = sessionHelper.GetSession("CurrentGreetingData") as Collection<Greeting>;
if (collGreeting.Count > 0)
{
Collection<CounterbySA> collCounterBySA = new ServiceFacade(User).SelectByFieldName<CounterbySA>("SAID", 106);//CurrentApplicationUser.id
if (collCounterBySA.Count > 0)
{
Counter counter = new ServiceFacade(User).SelectById<Counter>(collCounterBySA[0].CounterID);
Greeting greeting = collGreeting[0];
BoardQueue boardQueue = new BoardQueue();
boardQueue.BranchID = CurrentApplicationUser.BranchID;
boardQueue.CounterID = counter.ID;
boardQueue.SAID = 106; //CurrentApplicationUser.ID
boardQueue.PlatNumber = greeting.PlatNumber;
boardQueue.Status = (int)CallCustomerStatus.Open;
ResultStatus rs = new ServiceFacade(User).InsertBoardQueue(boardQueue);
voiceCall(string.Format("{0}di{1}", greeting.PlatNumber, counter.Name));
MessageBox.Show(string.Format("{0} Silahkan ke {1}", greeting.PlatNumber, counter.Name));
btnCall.Enabled = false;
btnReCall.Enabled = true;
btnComplete.Enabled = true;
sessionHelper.SetSession("CurrentCallData", boardQueue);
sessionHelper.SetSession("CurrentGreetingTemp", greeting);
}
else
{
MessageBox.Show("SA ini Belom terdaftar di Loket, Silahkan ke manu AssignSA untuk mendaftarkan/menempatkan SA ke Loket");
}
}
else
{
MessageBox.Show("Tidak Ada Customer Untuk Di panggil");
}
}
else if (isCurrentUser())
{
MessageBox.Show("sedang memanggil customer, click panggil ulang apabila customer belum datang");
btnCall.Enabled = true;
btnReCall.Enabled = true;
btnComplete.Enabled = true;
}
else
{
MessageBox.Show("SA lain sedang memanggil Customer, harap menunggu");
}
so if i click button call it will set the 2 session
and this where i get the session
protected void btnReCall_Click(Object sender, EventArgs e)
{
BoardQueue boardQueue = sessionHelper.GetSession("CurrentCallData") as BoardQueue;
if (boardQueue != null)
{
Counter counter = new ServiceFacade(User).SelectById<Counter>(boardQueue.CounterID);
voiceCall(string.Format("{0}di{1}", boardQueue.PlatNumber, counter.Name));
MessageBox.Show(string.Format("{0} Silahkan ke {1}", boardQueue.PlatNumber, counter.Name));
btnNext.Enabled = true;
}
else
{
MessageBox.Show("Harap Memanggil Customer terlebih Dahulu");
}
}
Before the page is refresh it works fine. but after the page refresh the session is gone.
i have done some research about this topic but i couldn't get the answer
Here are the get and set method for the session
public void SetSession(string sKey, object sValue)
{
HttpContext.Current.Session[sKey] = sValue;
AddSession(sKey, true);
}
public object GetSession(string sKey)
{
return ((object)(HttpContext.Current.Session[sKey]));
}
I am selecting a row from Gridview, working good except for checkbox, like I am assigning value of checkbox retreived from gridview to checkbox that is placed on web form but it isn't represented by checkbox on form, it shows empty checkbox in every case
if (gridviewDesignations.SelectedRow.Cells[5].Text == " ")
{
chkIsHead.Text = gridviewDesignations.SelectedRow.Cells[5].Text;
}
in short, checkbox is not picking value from gridview
Update:
tried this too:
CheckBox chkIsHead = (CheckBox) gridviewDesignations.SelectedRow.Cells[5].Controls[0];
if (chkIsHead.Checked == false)
{
chkIsHead.Checked = false;
}
else
{
chkIsHead.Checked = true;
}
Update:
my full code:
public partial class frmDesignations : System.Web.UI.Page
{
AccessibleVariables accessVariables = new AccessibleVariables(); //Used to access global variables
public void Clear(params TextBox[] txtBoxes)
{
foreach (TextBox txtbx in txtBoxes)
{
txtbx.Text = "";
}
}
public void fillddlDepartments()
{
ManageDepartmentsBizz mngDepBizz = new ManageDepartmentsBizz();
DataSet ds = (DataSet)mngDepBizz.SelectDepartments();
if (ds.Tables[0].Rows.Count != 0)
{
ddlDepartments.DataValueField = "DepID";
ddlDepartments.DataTextField = "DepName";
ddlDepartments.DataSource = ds.Tables[0];
// ddlDepartments.SelectedIndex = -1;
ddlDepartments.DataBind();
ddlDepartments.Items.Insert(0, "--Select--");
}
//else
// ddlDepartments.SelectedIndex = -1;
}
protected void Page_Load(object sender, EventArgs e)
{
if (Session.Count <= 0)
{
Response.Redirect("login.aspx");
}
lblMsgPopUp.Visible = false;
if (!IsPostBack)
{
fillddlDepartments();
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
try
{
int DepartmentID = Convert.ToInt32(ddlDepartments.SelectedValue);
bool IsHead = Convert.ToBoolean(chkIsHead.Checked);
DesignationsBizz DesigBizz = new DesignationsBizz(-1, txtTitle.Text, DepartmentID, txtContactNo.Text, IsHead);
//-1 is bogus,used to fill parameters criteria i.e no of params
ManageDesignationsBizz mngDesigBizz = new ManageDesignationsBizz();
bool Result = mngDesigBizz.Insert(DesigBizz);
if (Result == true)
{
HiddenFieldSetMessage.Value = "Saved";
HiddenFieldShowMessage.Value = "True";
Clear(txtTitle, txtSelectedID, txtContactNo);
}
else
{
HiddenFieldSetMessage.Value = "RecordAlreadyExists";
HiddenFieldShowMessage.Value = "True";
}
}
catch (Exception)
{
HiddenFieldSetMessage.Value = "NotSaved";
HiddenFieldShowMessage.Value = "True";
}
}
protected void btnSearchPopup_Click(object sender, EventArgs e)
{
string DesignationTitle = txtDesignationPopUp.Text;
ManageDesignationsBizz mngDepsBizz = new ManageDesignationsBizz();
DataSet ds = (DataSet)mngDepsBizz.Select(DesignationTitle);
if (ds.Tables[0].Rows.Count != 0)
{
lblMsgPopUp.Visible = false;
gridviewDesignations.DataSource = ds.Tables[0];
gridviewDesignations.DataBind();
gridviewDesignations.Visible = true;
}
else
{
lblMsgPopUp.Visible = true;
gridviewDesignations.Visible = false;
}
}
protected void gridviewDesignations_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
string DesignationTitle = txtDesignationPopUp.Text;
ManageDesignationsBizz mngDepBizz = new ManageDesignationsBizz();
DataSet ds = (DataSet)mngDepBizz.Select(DesignationTitle);
if (ds.Tables[0].Rows.Count != 0)
{
gridviewDesignations.PageIndex = e.NewPageIndex;
gridviewDesignations.DataSource = ds.Tables[0];
gridviewDesignations.DataBind();
gridviewDesignations.Visible = true;
}
}
protected void btnEdit_Click(object sender, EventArgs e)
{
if (gridviewDesignations.SelectedRow != null)
{
if (gridviewDesignations.SelectedRow.Cells[1].Text == " ")
{
txtSelectedID.Text = string.Empty;
}
else
{
txtSelectedID.Text = gridviewDesignations.SelectedRow.Cells[1].Text;
}
if (gridviewDesignations.SelectedRow.Cells[2].Text == " ")
{
txtTitle.Text = string.Empty;
}
else
{
txtTitle.Text = gridviewDesignations.SelectedRow.Cells[2].Text;
}
if (gridviewDesignations.SelectedRow.Cells[3].Text == " ")
{
ddlDepartments.SelectedValue = string.Empty;
}
else
{
ddlDepartments.SelectedValue = gridviewDesignations.SelectedRow.Cells[3].Text;
accessVariables.DepID = Convert.ToInt32(gridviewDesignations.SelectedRow.Cells[3].Text);
ViewState["depID"] = accessVariables.DepID;
}
if (gridviewDesignations.SelectedRow.Cells[4].Text == " ")
{
txtContactNo.Text = string.Empty;
}
else
{
txtContactNo.Text = gridviewDesignations.SelectedRow.Cells[4].Text;
}
CheckBox chkIsHead = (CheckBox) gridviewDesignations.SelectedRow.Cells[5].Controls[0];
if (chkIsHead.Checked == false)
{
chkIsHead.Checked = false;
}
else
{
chkIsHead.Checked = true;
}
gridviewDesignations.DataBind();
gridviewDesignations.SelectedIndex = -1;
HiddenFieldShowHideButtons.Value = "True";
}
}
protected void btnUpdatePopUp_Click(object sender, EventArgs e)
{
try
{
int id = Convert.ToInt32(txtSelectedID.Text);
int DepartmentID = Convert.ToInt32(ddlDepartments.SelectedValue);
bool IsHead = Convert.ToBoolean(chkIsHead.Checked);
DesignationsBizz DesigBizz = new DesignationsBizz(id, txtTitle.Text, DepartmentID, txtContactNo.Text, IsHead );
ManageDesignationsBizz mngDesigBizz = new ManageDesignationsBizz();
bool Result = mngDesigBizz.Update(DesigBizz);
if (Result == true)
{
HiddenFieldSetMessage.Value = "Updated";
HiddenFieldShowMessage.Value = "True";
Clear(txtSelectedID, txtTitle, txtContactNo);
}
else
{
HiddenFieldSetMessage.Value = "NotUpdated";
HiddenFieldShowMessage.Value = "True";
}
}
catch (Exception)
{
HiddenFieldSetMessage.Value = "NotUpdated";
HiddenFieldShowMessage.Value = "True";
}
}
protected void btnDeletePopUp_Click(object sender, EventArgs e)
{
try
{
int ID = Convert.ToInt32(txtSelectedID.Text.Trim());
ManageDesignationsBizz mngDepBizz = new ManageDesignationsBizz();
mngDepBizz.Delete(ID);
Clear(txtTitle, txtSelectedID, txtContactNo);
HiddenFieldSetMessage.Value = "Deleted";
HiddenFieldShowMessage.Value = "True";
}
catch (Exception)
{
HiddenFieldSetMessage.Value = "NotDeleted";
HiddenFieldShowMessage.Value = "True";
}
}
protected void btnClosePopup_Click(object sender, EventArgs e)
{
Clear(txtTitle, txtSelectedID, txtContactNo);
}
protected void ddlDepartments_SelectedIndexChanged(object sender, EventArgs e)
{
if (txtSelectedID.Text != "")
{
accessVariables.DepID = Convert.ToInt32(ddlDepartments.SelectedValue);
ViewState["depID"] = accessVariables.DepID;
}
else
{
accessVariables.DepID = Convert.ToInt32(ddlDepartments.SelectedValue);
ViewState["depID"] = accessVariables.DepID;
}
}
protected void chkIsHead_CheckedChanged(object sender, EventArgs e)
{
if (txtSelectedID.Text != "")
{
int DepID = Convert.ToInt32(ViewState["depID"]);
ManageDesignationsBizz mngDesig = new ManageDesignationsBizz();
bool isHead = mngDesig.SelectIsHeadExistsByDepID(DepID);
if (isHead == true)
{
HiddenFieldSetMessage.Value = "HeadExists";
HiddenFieldShowMessage.Value = "True";
chkIsHead.Checked = false;
}
}
else
{
int DepID = Convert.ToInt32(ViewState["depID"]);
ManageDesignationsBizz mngDesig = new ManageDesignationsBizz();
bool isHead = mngDesig.SelectIsHeadExistsByDepID(DepID);
if (isHead == true)
{
HiddenFieldSetMessage.Value = "HeadExists";
HiddenFieldShowMessage.Value = "True";
chkIsHead.Checked = false;
}
}
}
}
I believe the following is what you need to do:
Then select EditProgrammatically.
I'm not sure if yoou'll need to manually put data into the grid though but that won't be too hard. Examples can be seen here : http://msdn.microsoft.com/en-us/library/system.data.datatable(v=vs.110).aspx
PS : You can set the DataSource in the grid view to the DataTable.
i am working on an software in which i want to clear each thing after doing achieving a specific task, like clearing all the fields, list view etc etc and i've to write the a lot of things to be cleared off, like the code of my new button is:
private void btnNew_Click(object sender, EventArgs e)
{
txtProductCode1.ReadOnly = false;
txtInvoiceNo.ReadOnly = false;
cmbCustoemerType.Enabled = false;
cmbCustomerName.Enabled = false;
button1.Enabled = true;
txtProductCode1.Text = null;
txtWageName.Text = null;
txtWageCost.Text = null;
btnFirst.Visible = false;
btnPrevious.Visible = false;
btnNext.Visible = false;
btnLast.Visible = false;
cmbProductName.Enabled = true;
txtQty.ReadOnly = false;
txtPercant.ReadOnly = false;
txtDiscount.ReadOnly = false;
cmbCustoemerType.Enabled = true;
cmbCustomerName.Enabled = true;
button5.Enabled = true;
btnDelete.Enabled = true;
dtp1.Enabled = true;
btnSave.Text = "&Save";
cmbCustoemerType.Text = null;
cmbCustomerName.Text = null;
txtInvoiceNo.Clear();
txtDiscount.Clear();
txtGrandTotal.Clear();
txtProductName.Clear();
txtSalePrice.Clear();
txtQty.Clear();
txtTotal.Clear();
txtExtraWages.Text = null;
lvExtraWages.Items.Clear();
lvTransaction.Items.Clear();
lblCount.Text = null;
lblNetTotal.Text = null;
txtPercant.Text = null;
txtInvoiceNo.Text = invoice.ToString();
}
is there any way to get rid of writing the code again n again, like i need to enable one thing which i've disabled here on another button so i have to write reverse code of this to achieve the task and it's really annoying! is there any other way to do this?
EDIT:
tried following code:
private void btnNew_Click(object sender, EventArgs e)
{
//using setboxdefault function
SetTextBoxDefaults();
cmbCustoemerType.Text = null;
cmbCustomerName.Text = null;
cmbCustoemerType.Enabled = false;
cmbCustomerName.Enabled = false;
cmbProductName.Enabled = true;
cmbCustoemerType.Enabled = true;
cmbCustomerName.Enabled = true;
button5.Enabled = true;
btnDelete.Enabled = true;
button1.Enabled = true;
btnFirst.Visible = false;
btnPrevious.Visible = false;
btnNext.Visible = false;
btnLast.Visible = false;
btnSave.Text = "&Save";
lvExtraWages.Items.Clear();
lvTransaction.Items.Clear();
lblCount.Text = null;
lblNetTotal.Text = null;
dtp1.Enabled = true;
txtInvoiceNo.Text = invoice.ToString();
}
private void SetTextBoxDefaults()
{
var textBoxes = GetControls(this, typeof(TextBox));
foreach (var textBox in textBoxes)
{
TextBox.Clear();
}
}
public IEnumerable<Control> GetControls(Control control, Type type)
{
var controls = control.Controls.Cast<Control>();
return controls.SelectMany(ctrl => GetControls(ctrl, type)).Concat(controls).Where(c => c.GetType() == type);
}
but it's giving error on TextBox.Clear(); , error is Error 4
An object reference is required for the non-static field, method, or property 'System.Windows.Forms.TextBoxBase.Clear()'
Please let me know where i am mistaking..!!
As Tim has suggested, you can iterate though the controls and set each one accordingly..
public IEnumerable<Control> GetControls(Control control,Type type)
{
var controls = control.Controls.Cast<Control>();
return controls.SelectMany(ctrl => GetControls(ctrl,type)).Concat(controls).Where(c => c.GetType() == type);
}
private void btnNew_Click(object sender, EventArgs e)
{
SetComboBoxDefaults();
SetTextBoxDefaults();
SetButtonDefaults();
}
private void SetComboBoxDefaults()
{
var comboBoxes = GetControls(this, typeof(ComboBox));
foreach (var comboBox in comboBoxes)
{
((ComboBox)comboBox).Enabled = false;
((ComboBox)comboBox).Text = null;
}
}
private void SetTextBoxDefaults()
{
var textBoxes = GetControls(this, typeof(TextBox));
foreach (var textBox in textBoxes)
{
((TextBox)textBox).Clear();
}
}
private void SetButtonDefaults()
{
var buttons = GetControls(this, typeof(Button));
foreach (var button in buttons)
{
((Button)button).Visible = false;
if (button.Name == "btnSave") ((Button)button).Text = "&Save";
}
}
You can also have separate GetControl methods so that it returns a specific type of Control, reducing the need to cast to derived types.
update for edit:
You are using the TextBox type instead of the variable name in the foreach loop. Update it to use textBox (lowercase), not TextBox (pascal) see below:
private void SetTextBoxDefaults()
{
var textBoxes = GetControls(this, typeof(TextBox));
foreach (var textBox in textBoxes)
{
((TextBox)textBox).Clear();
}
}
Remember to stay DRY
Don't
Repeat
Yourself
Partition the reset logic into suitable, small methods that reset a logical grouping of controls. Then invoke those methods where and as needed.
What I have done in several such cases is this:
void SetTextBoxReadOnly(bool val, param TextBox[] textBoxes)
{
if(textBoxes != null && textBoxes.Length > 0)
{
foreach(TextBox textBox in textBoxes)
{
if(textBox != null)
{
textBox.ReadOnly = val;
}
}
}
}
void SetControlEnabled(bool val, param Control[] ctrls)
{
if(ctrls != null && ctrls.Length > 0)
{
foreach(Control ctrl in ctrls)
{
if(ctrl != null)
{
ctrl.Enabled = val;
}
}
}
}
// etc set of methods for similar situations.
// there methods can be invoked as
...
...
...
SetTextBoxReadOnly(true, txtProductCode1,
txtInvoiceNo,
txtQty,
txtPercant,
txtDiscount);
For file transfer between the client and server systems we have a GUI designed on the client system using C# windows forms. We have added a lot of background images and text boxes to make the GUI impressive. But whenever we execute the client code, the GUI takes a few seconds to load itself and be stable , before a choice from the GUI can be made. This happens after every request made from the client side GUI.(its like all the form elements vanish and appear again in a short span of time ). Please help with this. May i know the reason for it.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
namespace Client405
{
public partial class RequestForm : Form
{
#region Variables
internal static ListBox FileListBox;
internal static byte[] RecievedFile = new byte[46000000];
internal static string StoragePath = string.Empty;
internal static bool CacheSelected = false;
internal static string ChosenTech = "Default";
internal static bool EnableCompression = false;
//internal static string FileType;
internal static string SelectedFile = string.Empty;
internal static Stopwatch watch = new Stopwatch();
#endregion
public RequestForm()
{
InitializeComponent();
this.Load += new EventHandler(RequestForm_Load);
this.DoubleBuffered = true;
}
void RequestForm_Load(object sender, EventArgs e)
{
ComprMsgLabel.Text = "Compression Technique chosen is :" + ChosenTech;
FileListBox = new ListBox();
FileName_textBox.Enabled = true;
FileName_textBox.ReadOnly = true;
if (!Connections.SocketConnected())
{
Connections.EstablishConnectionWithServer();
}
if (LoginAuthenticator.registered)
{
EnableCompression = true;
CacheSelected = true;
RegisterlinkLabel.Visible = false;
HighRB.Enabled = true;
LowRB.Enabled = true;
MediumRB.Enabled = true;
CacheMsg_label.Text = "Caching Enabled";
}
else if (!LoginAuthenticator.registered)
{
RegisterlinkLabel.Visible = true;
RegisterlinkLabel.Show();
Logout_Label.Text = "Home Page";
Cache_checkBox.CheckState = CheckState.Unchecked;
Cache_checkBox.Enabled = false;
EnableCompr_checkBox.Enabled = false;
HighRB.Enabled = false;
LowRB.Enabled = false;
MediumRB.Enabled = false;
DefaultRB.Visible = false;
NoneRB.Visible = false;
DefaultRB.Enabled = false;
NoneRB.Enabled = false;
CacheMsg_label.Text = "Caching Disabled";
}
ChosenTech = "None";
LogUser_Label.Text = LogUser_Label.Text + LoginAuthenticator.myCurrentUser;
SetClientInfo();
}
private void SetClientInfo()
{
//LogUser_Label.Text = LoginAuthenticator.myCurrentUser;
HostValue_Label.Text = HelperInfo.HostNameValue;
//Add port info
Port_Value.Text = HelperInfo.PortNumber;
//Add IP address
IPAddr_value.Text = HelperInfo.IPAddress_client;
//Add Gateway info
Gateway_value.Text = HelperInfo.Default_Gateway;
//Add the ip address of server connected to
ServerIP_Value_Label.Text = HelperInfo.Connected_To(Connections.myClientSocket);
if (Connections.myClientSocket.Connected)
{
ONOFF_radio.Text = "Online";
}
else
{
ONOFF_radio.Text = "Offline";
}
}
private void GetFile_Button_Click(object sender, EventArgs e)
{
if ((AudioRB.Checked == false) && (ImageRB.Checked == false) && (TextRB.Checked == false))
{
MessageBox.Show("Please select a File Type");
return;
}
if (SelectedFile == string.Empty)
{
MessageBox.Show("Please Select a File");
return;
}
if (!LoginAuthenticator.registered)
{
FileTransfer.UnRegisteredTransfer();
this.Refresh();
MessageBox.Show("Transaction Completed");
}
if (LoginAuthenticator.registered)
{
DialogResult trans_reqd = DialogResult.No;
//check Cache
if (Cache_checkBox.CheckState == CheckState.Checked)
{
trans_reqd = FileCache.TransactionQuery(RequestForm.SelectedFile);
if (trans_reqd == DialogResult.No)
{
string[] files = { System.IO.Path.Combine(#"D:\\FT\\Cache", RequestForm.SelectedFile), System.IO.Path.Combine(#"D:\\FT\\Downloads", RequestForm.SelectedFile) };
if (System.IO.File.Exists(files[1]))
{
System.IO.File.Delete(files[1]);
}
System.IO.File.Copy(files[0], files[1]);
watch.Stop();
}
else //if not in cacheF
{
FileTransfer.RegisteredTransfer();
}
}
else //if caching not enabled
{
FileTransfer.RegisteredTransfer();
}
this.Refresh();
MessageBox.Show("Transaction Completed");
}
}
private void AudioRB_CheckedChanged(object sender, EventArgs e)
{
ChosenTech = "Default";
if (AudioRB.Checked == true)
{
ImageRB.Checked = false;
TextRB.Checked = false;
EnableCompr_checkBox.CheckState = CheckState.Unchecked;
EnableCompr_checkBox.Visible = false;
EnableCompr_checkBox.Enabled = false;
FileListBox.Hide();
DisplayRadioButtons();
SelectedFile = string.Empty;
FileName_textBox.Text = string.Empty;
FileTransfer.FileType = "Audio";
//ViewFiles_button.Visible = true;
ViewFiles();
}
else if (AudioRB.Checked == false)
{
//ViewFiles_button.Visible = false;
EnableCompr_checkBox.Visible = true;
EnableCompr_checkBox.Enabled = true;
FileListBox.Hide();
}
}
private void ViewFiles()
{
FileTransfer.GetFileNames();
this.Controls.Add(RequestForm.FileListBox);
RequestForm.FileListBox.BringToFront();
RequestForm.FileListBox.Visible = true;
RequestForm.FileListBox.SelectedIndexChanged += new EventHandler(listBox1_SelectedIndexChanged);
//RequestForm.SelectedFile = FileTransfer.FileListView.SelectedItems[0].Text;
//FileName_textBox.Text = RequestForm.SelectedFile;
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
FileName_textBox.Text = FileListBox.SelectedItem.ToString();
RequestForm.SelectedFile = FileName_textBox.Text;
}
private void ImageRB_CheckedChanged(object sender, EventArgs e)
{
ChosenTech = "Default";
if (ImageRB.Checked == true && LoginAuthenticator.registered)
{
AudioRB.Checked = false;
TextRB.Checked = false;
EnableCompr_checkBox.CheckState = CheckState.Unchecked;
EnableCompr_checkBox.Enabled = true;
EnableCompr_checkBox.Visible = true;
FileListBox.Hide();
FileTransfer.FileType = "Image";
SelectedFile = string.Empty;
FileName_textBox.Text = string.Empty;
DisplayRadioButtons();
ViewFiles();
//ViewFiles_button.Visible = true;
}
else if (ImageRB.Checked == true && !LoginAuthenticator.registered)
{
AudioRB.Checked = false;
TextRB.Checked = false;
EnableCompr_checkBox.CheckState = CheckState.Unchecked;
EnableCompr_checkBox.Enabled = false;
EnableCompr_checkBox.Visible = true;
FileListBox.Hide();
FileTransfer.FileType = "Image";
SelectedFile = string.Empty;
FileName_textBox.Text = string.Empty;
DisplayRadioButtons();
ViewFiles();
}
else if (ImageRB.Checked == false)
{
//ViewFiles_button.Visible = false;
RequestForm.FileListBox.Hide();
}
}
private void TextRB_CheckedChanged(object sender, EventArgs e)
{
ChosenTech = "Default";
if (TextRB.Checked == true && LoginAuthenticator.registered)
{
ImageRB.Checked = false;
AudioRB.Checked = false;
EnableCompr_checkBox.CheckState = CheckState.Unchecked;
EnableCompr_checkBox.Enabled = true;
EnableCompr_checkBox.Visible = true;
RequestForm.FileListBox.Hide();
DisplayRadioButtons();
FileTransfer.FileType = "Text";
SelectedFile = string.Empty;
FileName_textBox.Text = string.Empty;
ViewFiles();
//ViewFiles_button.Visible = true;
}
else if (TextRB.Checked == true && !LoginAuthenticator.registered)
{
ImageRB.Checked = false;
AudioRB.Checked = false;
EnableCompr_checkBox.CheckState = CheckState.Unchecked;
EnableCompr_checkBox.Enabled = false;
EnableCompr_checkBox.Visible = true;
RequestForm.FileListBox.Hide();
DisplayRadioButtons();
FileTransfer.FileType = "Text";
SelectedFile = string.Empty;
FileName_textBox.Text = string.Empty;
ViewFiles();
}
else if (TextRB.Checked == false)
{
//ViewFiles_button.Visible = false;
RequestForm.FileListBox.Hide();
}
}
private void Cache_checkBox_CheckedChanged(object sender, EventArgs e)
{
if (Cache_checkBox.Checked)
{
CacheMsg_label.Text = "Caching Enabled";
CacheSelected = true;
}
else
{
CacheMsg_label.Text = "Caching Disabled";
CacheSelected = false;
}
}
private void EnableCompr_checkBox_CheckedChanged(object sender, EventArgs e)
{
DisplayRadioButtons();
}
internal void DisplayRadioButtons()
{
if (EnableCompr_checkBox.CheckState == CheckState.Unchecked)
{
HighRB.Enabled = false;
MediumRB.Enabled = false;
LowRB.Enabled = false;
HighRB.Visible = false;
MediumRB.Visible = false;
LowRB.Visible = false;
DefaultRB.Enabled = false;
DefaultRB.Visible = false;
NoneRB.Enabled = false;
NoneRB.Visible = false;
}
if (EnableCompr_checkBox.Checked && FileTransfer.FileType == null)
{
MessageBox.Show("Please select a FileType.\nAssociated Compression techniques available will be shown.");
EnableCompr_checkBox.CheckState = CheckState.Unchecked;
}
if (EnableCompr_checkBox.Checked && FileTransfer.FileType == "Text" && LoginAuthenticator.registered)
{
DefaultRB.Enabled = true;
DefaultRB.Visible = true;
NoneRB.Visible = true;
NoneRB.Enabled = true;
HighRB.Enabled = false;
MediumRB.Enabled = false;
LowRB.Enabled = false;
HighRB.Visible = false;
MediumRB.Visible = false;
LowRB.Visible = false;
ComprMsgLabel.Text = "Chosen Compression technique : Default";
}
else if (EnableCompr_checkBox.Checked && FileTransfer.FileType == "Text" && !LoginAuthenticator.registered)
{
HighRB.Enabled = false;
MediumRB.Enabled = false;
LowRB.Enabled = false;
HighRB.Visible = false;
MediumRB.Visible = false;
LowRB.Visible = false;
NoneRB.Visible = false;
DefaultRB.Visible = false;
ComprMsgLabel.Text = "Chosen Compression technique : Default";
}
else if (EnableCompr_checkBox.Checked && FileTransfer.FileType == "Image" && LoginAuthenticator.registered)
{
DefaultRB.Enabled = true;
DefaultRB.Visible = true;
NoneRB.Visible = true;
NoneRB.Enabled = true;
HighRB.Enabled = true;
MediumRB.Enabled = true;
LowRB.Enabled = true;
HighRB.Visible = true;
MediumRB.Visible = true;
LowRB.Visible = true;
ChosenTech = "Default";
ComprMsgLabel.Text = "Chosen Compression technique : Default";
}
else if (EnableCompr_checkBox.Checked && FileTransfer.FileType == "Image" && !LoginAuthenticator.registered)
{
HighRB.Enabled = false;
MediumRB.Enabled = false;
LowRB.Enabled = false;
HighRB.Visible = false;
MediumRB.Visible = false;
LowRB.Visible = false;
DefaultRB.Visible = false;
NoneRB.Visible = false;
DefaultRB.Enabled = false;
NoneRB.Enabled = false;
ChosenTech = "VLOW";
ComprMsgLabel.Text = "Chosen Compression technique : " + ChosenTech;
}
}
private void NoneRB_CheckedChanged(object sender, EventArgs e)
{
if (FileTransfer.FileType == "Text" && NoneRB.Checked == true)
{
ChosenTech = "None";
DefaultRB.Checked = false;
}
else if (FileTransfer.FileType == "Image" && NoneRB.Checked == true)
{
ChosenTech = "None";
DefaultRB.Checked = false;
HighRB.Checked = false;
LowRB.Checked = false;
MediumRB.Checked = false;
}
else if (NoneRB.Checked == false)
{
ChosenTech = "Default";
}
ComprMsgLabel.Text = "Compression Technique chosen is :" + ChosenTech;
}
private void Logout_Label_Click(object sender, EventArgs e)
{
Connections.EndConnectionWithServer();
Form1 newForm = new Form1();
LoginAuthenticator.myCurrentUser = string.Empty;
ChosenTech = string.Empty;
FileTransfer.FileType = null;
this.Hide();
newForm.Show();
MessageBox.Show("LogOut successful");
}
private void MediumRB_CheckedChanged(object sender, EventArgs e)
{
if (MediumRB.Checked == true)
{
ChosenTech = "MEDIUM";
HighRB.Checked = false;
LowRB.Checked = false;
NoneRB.Checked = false;
}
else if (MediumRB.Checked == false)
{
ChosenTech = "Default";
}
ComprMsgLabel.Text = "Compression Technique chosen is :" + ChosenTech;
}
private void LowRB_CheckedChanged(object sender, EventArgs e)
{
if (LowRB.Checked == true)
{
ChosenTech = "LOW";
HighRB.Checked = false;
MediumRB.Checked = false;
NoneRB.Checked = false;
}
else if (LowRB.Checked == false)
{
ChosenTech = "Default";
}
ComprMsgLabel.Text = "Compression Technique chosen is :" + ChosenTech;
}
private void HighRB_CheckedChanged(object sender, EventArgs e)
{
if (HighRB.Checked == true)
{
ChosenTech = "HIGH";
LowRB.Checked = false;
MediumRB.Checked = false;
NoneRB.Checked = false;
}
else if (HighRB.Checked == false)
{
ChosenTech = "Default";
}
ComprMsgLabel.Text = "Compression Technique chosen is :" + ChosenTech;
}
private void statistics_button_Click(object sender, EventArgs e)
{
Form2 statForm = new Form2();
statForm.fileType_label.Text = statForm.fileType_label.Text + FileTransfer.FileType;
statForm.fnstat_label.Text = statForm.fnstat_label.Text + SelectedFile;
statForm.ASize_label.Text = statForm.ASize_label.Text + " " + FileTransfer.actualSize + " bytes";
statForm.recSize_label.Text = statForm.recSize_label.Text + " " + FileTransfer.recSize + " bytes";
statForm.rtt_label.Text = statForm.rtt_label.Text + " " + watch.ElapsedMilliseconds + " ms";
long percentage = ((FileTransfer.actualSize - FileTransfer.recSize) * 100) / FileTransfer.actualSize;
statForm.BWsave.Text = statForm.BWsave.Text + " " + percentage + " %";
statForm.Show();
if (watch.ElapsedMilliseconds > 0)
{
MessageBox.Show("The time taken for the transaction is : " + watch.ElapsedMilliseconds);
}
else
{
MessageBox.Show("The time taken for the transaction is : 1000 ");
}
}
private void Folder_Select_Button_Click(object sender, EventArgs e)
{
SaveFileDialog sd = new SaveFileDialog();
sd.InitialDirectory = #"D:\FT\";
sd.Filter = "Text files (*.txt)|*.txt|ImageFiles (*.jpg)|*.jpg | Audio Files (*.mp3)|*.mp3";
sd.ShowDialog();
if (!File.Exists(sd.FileName))
{
FileStream fs = File.Create(sd.FileName);
fs.Close();
}
else
{
FileStream fd = File.Open(sd.FileName, FileMode.OpenOrCreate);
fd.Close();
}
StoragePath = sd.FileName;
}
private void RegisterlinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
Connections.EndConnectionWithServer();
//MessageBox.Show("Please Enter the Registration Details. ");
Register regForm = new Register();
regForm.Show();
this.Hide();
}
private void refresh_Click(object sender, EventArgs e)
{
if (FileTransfer.FileType == null)
{
MessageBox.Show("Select a File Type");
}
else
{
ViewFiles();
}
}
private void Setting_Label_Click(object sender, EventArgs e)
{
Process myprocess = new Process();
try
{
myprocess.StartInfo.UseShellExecute = true;
myprocess.StartInfo.FileName = "http://" + HelperInfo.Default_Gateway + "//WANem";
myprocess.Start();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private void FileName_textBox_TextChanged(object sender, EventArgs e)
{
}
}
}
Try using below code in your form constructor.
this.DoubleBuffered = true;
It should improve some performance. Windows forms are not made to display lot of images overlapped on each other.
I have been looking all over the Internet for this and have found similar, but none of it will work for me. Everything I have found assumes the listbox is on the main form and not the secondary form, or the code is for an older version of C# or Visual Studio (I am using VS2008).
I am creating a web browser that has a button on the main form (called frmMyBrowser) to open a dialog (frmBookmarks) with a listbox (lstBookmark) with bookmarked URLs. I need to be able to double click on an item (the bookmarked URL) and have the text pasted into the address bar (cmbAddress) of the main form.
Any help would be GREATLY appreciated.
I figured out that if I create the window at runtime, I can get it to work. In case anyone is interested, the code I used is below.
public void frmMyBrowser_ShowFavorites(object sender, EventArgs e)
{
frmFavorites.ShowIcon = false;
frmFavorites.ShowInTaskbar = false;
frmFavorites.MinimizeBox = false;
frmFavorites.MaximizeBox = false;
frmFavorites.ControlBox = false;
frmFavorites.Text = "Bookmarks";
frmFavorites.Width = 500;
frmFavorites.Height = 350;
frmFavorites.Controls.Add(lstFavorites);
frmFavorites.Controls.Add(btnRemoveFavorite);
frmFavorites.Controls.Add(btnAddFavorite);
frmFavorites.Controls.Add(btnCloseFavorites);
frmFavorites.Controls.Add(txtCurrentUrl);
lstFavorites.Width = 484;
lstFavorites.Height = 245;
btnRemoveFavorite.Location = new Point(8, 280);
btnAddFavorite.Location = new Point(8, 255);
btnCloseFavorites.Location = new Point(400, 255);
txtCurrentUrl.Location = new Point(110, 255);
txtCurrentUrl.Size = new Size(255, 20);
btnAddFavorite.Text = "Add";
btnRemoveFavorite.Text = "Remove";
btnCloseFavorites.Text = "Close";
txtCurrentUrl.Text = wbBrowser.Url.ToString();
btnAddFavorite.Click += new EventHandler(btnAddFavorite_Click);
btnRemoveFavorite.Click += new EventHandler(btnRemoveFavorite_Click);
frmFavorites.Load += new EventHandler(frmFavorites_Load);
btnCloseFavorites.Click += new EventHandler(btnCloseFavorites_Click);
lstFavorites.MouseDoubleClick += new MouseEventHandler(lstFavorites_MouseDoubleClick);
frmFavorites.Show();
}
public void btnCloseFavorites_Click(object sender, EventArgs e)
{
if (lstFavorites.Items.Count > 0)
{
using (StreamWriter writer = new System.IO.StreamWriter(#Application.StartupPath + "\\favorites.txt"))
{
for (int i = 0; i < lstFavorites.Items.Count; i++)
{
writer.WriteLine(lstFavorites.Items[i].ToString());
}
writer.Close();
}
}
frmFavorites.Hide();
}
public void btnAddFavorite_Click(object sender, EventArgs e)
{
string strFavoriteAddress = wbBrowser.Url.ToString();
if (!lstFavorites.Items.Contains(strFavoriteAddress))
{
lstFavorites.Items.Add(strFavoriteAddress);
MessageBox.Show("Favorite Added", "Message");
}
else if (lstFavorites.Items.Contains(strFavoriteAddress))
{
MessageBox.Show("This site already exists in your Favorites list!", "Error");
}
else
{
}
}
public void btnRemoveFavorite_Click(object sender, EventArgs e)
{
try
{
lstFavorites.Items.RemoveAt(lstFavorites.SelectedIndices[0]);
}
catch
{
MessageBox.Show("You need to select an item", "Error");
}
}
public void frmFavorites_Load(object sender, EventArgs e)
{
try
{
using (StreamReader reader = new System.IO.StreamReader(#Application.StartupPath + "\\favorites.txt"))
{
while (!reader.EndOfStream)
{
for (int i = 0; i < 4; i++)
{
string strListItem = reader.ReadLine();
if (!String.IsNullOrEmpty(strListItem))
{
lstFavorites.Items.Add(strListItem);
}
}
}
reader.Close();
}
}
catch
{
MessageBox.Show("An error has occured", "Error");
}
}
private void lstFavorites_MouseDoubleClick(object sender, MouseEventArgs e)
{
string strSelectedAddress = lstFavorites.Text.ToString();
cmbAddress.Text = strSelectedAddress;
wbBrowser.Navigate(strSelectedAddress);
frmFavorites.Hide();
}