I a have a page that has enumtype. the following is the code in aspx.cs inside the pageload
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
RegardingObject();
ListItem selectedType = dropRegarding.Items.FindByValue(Event.RegardingObjectType.ToString());
if(selectedType!=null)
{
selectedType.Selected = true;
}
the following to populate dropdownlist
private void RegardingObject()
{
dropRegarding.Items.Add(new ListItem("UnknownOrNone","0"));
dropRegarding.Items.Add(new ListItem("LiveTrack", "10"));
dropRegarding.Items.Add(new ListItem("Activity", "11"));
}
while saving it back i am using
Event.RegardingObjectType = (EnumTypes)Enum.Parse(typeof(EnumTypes),
dropRegarding.SelectedItem.ToString());
getting cannot implicitly convert type 'datacontracts.enumtypes' to 'datacontracts.enumtypes.regardingobjecttype'
in datacontracts.enumtypes.cs i have
public class EnumTypes
{
public enum RegardingObject
{
UnknownOrNone = 0,
LiveTrack = 10,
Activity = 11
}
}
That's because EnumTypes isn't an enum, RegardingObject is:
Event.RegardingObjectType = (EnumTypes.RegardingObject)Enum.Parse(typeof(EnumTypes.RegardingObject),
dropRegarding.SelectedItem.ToString());
this does it
Event.RegardingObjectType = (EnumTypes.RegardingObjectType)Enum.Parse(typeof(EnumTypes.RegardingObjectType),
dropRegarding.SelectedItem.ToString());
its EnumTypes.regardingobjecttype instead of enumtypes
Related
I have two form:
the first one "FrmAddRecordOfNonComplianceQHSE" has in load event this code
private async void FrmAddRecordOfNonComplianceQHSE_Load(object sender, EventArgs e)
{
KeyPreview = true;
txtCreationDate.EditValue = DateTime.Today;
DataTable DDt = await qhse.GetLastQHSEOrderNumberRecordOfNonCompliance().ConfigureAwait(true);
string RatingNumber = DDt.Rows[0][0].ToString();
txtOrderNumber.Text = RatingNumber;
cmbDetecteurStructure.Properties.DataSource = await qhse.GetEmployeesByDepartmentID(Program.FK_Department).ConfigureAwait(true);
cmbDetecteurStructure.Properties.DisplayMember = "Nom et Prénom";
cmbDetecteurStructure.Properties.ValueMember = "Matricule";
cmbRelevantStructure.Properties.DataSource = await qhse.Get_Department().ConfigureAwait(true);
cmbRelevantStructure.Properties.DisplayMember = "Département";
cmbRelevantStructure.Properties.ValueMember = "ID_Department";
}
and I have this code also
private void cmbRelevantStructure_Closed(object sender, ClosedEventArgs e)
{
BeginInvoke(new MethodInvoker(() => { cmbRelevantEmployee.EditValue = null; }));
}
private async void cmbRelevantEmployee_Enter(object sender, EventArgs e)
{
try
{
cmbRelevantEmployee.Properties.DataSource = await qhse.GetManagerByDepartmentID(Convert.ToInt32(cmbRelevantStructure.EditValue, CultureInfo.CurrentCulture)).ConfigureAwait(true);
cmbRelevantEmployee.Properties.DisplayMember = "Nom et Prénom";
cmbRelevantEmployee.Properties.ValueMember = "Matricule";
}
catch { }
}
and about the second form "FrmRecordOfNonComplianceQHSE" I have this code
FrmAddRecordOfNonComplianceQHSE frmQHSE = new FrmAddRecordOfNonComplianceQHSE();
and on DoubleClick of gridView1 I have this code
private async void gridView1_DoubleClick(object sender, EventArgs e)
{
//frmQHSE.cmbDetecteurStructure.Properties.DataSource = null;
frmQHSE.cmbDetecteurStructure.EditValue = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "FKDetecteur");
frmQHSE.txtCreationDate.EditValue = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "CreationDate");
frmQHSE.txtOrderNumber.Text = string.Empty;
frmQHSE.txtOrderNumber.Text = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "OrderNumber").ToString();
frmQHSE.cmbRelevantStructure.EditValue = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "RelevantDepartment");
frmQHSE.cmbRelevantEmployee.Enter += new EventHandler(cmbRelevantEmployee_Enter);
frmQHSE.cmbRelevantEmployee.EditValue = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "FKRelevant");
if (frmQHSE == null || frmQHSE.IsDisposed)
frmQHSE = new FrmAddRecordOfNonComplianceQHSE();
frmQHSE.ShowDialog();
}
and I have this code also
private async void cmbRelevantEmployee_Enter(object sender, EventArgs e)
{
try
{
frmQHSE.cmbRelevantEmployee.Properties.DataSource = await qhse.GetManagerByDepartmentID(Convert.ToInt32(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "RelevantDepartment"), CultureInfo.CurrentCulture)).ConfigureAwait(true);
frmQHSE.cmbRelevantEmployee.Properties.DisplayMember = "Nom et Prénom";
frmQHSE.cmbRelevantEmployee.Properties.ValueMember = "Matricule";
}
catch { }
}
Now when I DoubleClick on gridView1 row the first form open but the controls get the values from the load event of that form not the values of gridView1 of my second form.
How can solve this problem ?.
Thanks in advance.
Either use data binding and assign an object to DataSource or assign values to the controls, but do not mix both approaches.
I assume that GetManagerByDepartmentID now returns a DataTable or something like this, since you have display member names with spaces. Create data classes instead. This makes it easier to manipulate the data. Something like this
public class Employee
{
public string NomPrénom { get; set; }
public int Matricule { get; set; }
public string Département { get; set; }
public int ID_Department { get; set; }
...
}
Now, you can let GetManagerByDepartmentID return an Employee object. Your form binds to an Employee object and your grid can bind to an Employee object. Or at least you can create and fill such an object manually and assign it to the DataSource of the first form.
private async void gridView1_DoubleClick(object sender, EventArgs e)
{
var emp = new Employee {
FKDetecteur = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "FKDetecteur"),
CreationDate = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "CreationDate"),
OrderNumber gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "OrderNumber").ToString(),
....
};
frmQHSE.EmployeeBindingSource.DataSource = emp;
frmQHSE.ShowDialog();
}
Use BindingSourcees in conjunction with object data sources on your from. This allows you to set DisplayMembers and ValueMembers in the forms designer.
I have this code on my asp net page (it´s an url with an id www.example.com/GestHC.aspx?pID=36006394 )
public partial class GestHC : WebPart
{
public GestHC ()
{
}
static int iIDHC;
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
InitializeControl();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!this.Page.IsPostBack)
{
iIDHC = -1;
string str = this.Page.Request["pID"];
iIDHC = int.Parse(str.Replace("'", ""));
MyModel hc = MyModel.readdata(iIDHC);
this.txtName.text = hc.name
this.txtSurname.text = hc.surname
...
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
try
{
MyModel hc = new MyModel();
if (iIDHC != -1)
{
hc = MyModel.readdata(iIDHC);
}
else
{
hc.name = txtname.text;
hc.surname = txtSurname.text;
}
hc.dir1 = dir.text;
...
hc.savedata()
}
catch (Exception)
{
this.navegarAGridMensaje("Error");
}
}
}
The problem is that when user loads the data and saves it, everything works fine but when more than 2 user or browsers works together the data is mixed. For example:
User a creates:
ID = 10
Name = XXX
Age = 8
User b creates:
ID = 11
Name = YYY
Age = 10
Then if user a updates his data (ID=10), maybe setting the Age to 80 the result is
User a creates:
ID = 10
Name = XXX
Age = 8
User b creates:
ID = 11
Name = YYY
Age = 88
So the (ID=11) is updated. Debuggin.. I could see that with an static id, when the second user loads it can read the previous user iIDHC....
How to avoid this problem?
You can use Session object instead (https://msdn.microsoft.com/en-us/library/ms178581.aspx).
When you are store your data in static variable - it will be shared between all users in your app.
Make it non static!
public partial class GestHC : WebPart
{
public GestHC ()
{
}
private int iIDHC = -1;//initialize here
...
}
also you dont have to initialize in page load
protected void Page_Load(object sender, EventArgs e)
{
//iIDHC = -1; - not required as you can initialize it during declaration
}
I am trying to store multiple values from numerous buttons so I can return values of two or more things e.g. if chocolate and vanilla clicked both prices and names can be returned. I will also need to make calculations on the data set later. Whenever I return the data only the most recent values return rather than all of those I have selected.
private void VanillaBtn_Click(object sender, RoutedEventArgs e)
{
items.Price = 450;
items.Name = "Vanilla"
}
private void ChocolateBtn_Click(object sender, RoutedEventArgs e)
{
items.Price = 500;
items.Name = "Chocolate";
}
This is my class, any help or tips would be appreciated.
class Items
{
private int thePrice;
private string theName;
public int Price
{
get
{
return thePrice;
}
set
{
thePrice = value ;
}
}
public string Name
{
get
{
return theName;
}
set
{
theName = value;
}
}
Keep a list of whatever was clicked.
private List<Items> selectedItems = new List<Items>();
So, every time something is clicked, you store the object in the list defined above.
private void VanillaBtn_Click(object sender, RoutedEventArgs e)
{
var newItem = new Items();
newItem.Price = 450;
newItem.Name = "Vanilla";
selectedItems.Add(newItem);
}
I am making an online form. I initialise 4 variables in my code at the beginning. When I select a dropdown, an event (DropDownList4_SelectedIndexChanged ) gets fired which in turn call Availability(). Here my boolean variable avail_bus is assigned a value. However, when i click on submit button ( Button1_Click1), the variable avail_bus is reinitialised to false. I debugged this and found out that upon clicking on Submit(Button1_Click1) the control first goes to the top of the code in the page which is
public partial class Appform : System.Web.UI.Page
{
private bool isNotDup = true;
private bool avail_bus ;
private int max_capacity_bus;
private int realAvailability;
}
and then goes to Button1_click1 .
How can I prevent this from happening ? If the state of avail_bus is changed to true while calling availability, it should not get reinitialized to true when i click on submit.
Below is my code :
namespace eTransport
{
public partial class Appform : System.Web.UI.Page
{
private bool isNotDup = true;
private bool avail_bus ;
private int max_capacity_bus;
private int realAvailability;
protected void Page_Load (object sender, EventArgs e)
{
if (!this.IsPostBack)
{
BindDropDown();
}
}
//Method called when dropdown is selected in Bus Stop. It helps to populate Bus Number
protected void DropDownList4_SelectedIndexChanged (object sender, EventArgs e)
{
AutoPopulateBusStop();
Availability();
}
//Method to load drop down values in Bus Stop. These are populated from database
protected void BindDropDown ()
{
//some code here
}
//Method to autopopulate Bus Number based on selection of Bus Stop. The mapping is in the database in the table named -> dropdownlist
protected void AutoPopulateBusStop ()
{
//some code here
}
protected void Availability ()
{
string constr5 = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
using (SqlConnection con5 = new SqlConnection(constr5))
{
try
{
using (SqlCommand cmd5 = new SqlCommand("select count(*) from etms where BusNo='" + TextBox6.Text.ToString() + "'"))
{
cmd5.CommandType = CommandType.Text;
cmd5.Connection = con5;
con5.Open();
int capacity_from_db = Convert.ToInt16(cmd5.ExecuteScalar());
realAvailability = max_capacity_bus - capacity_from_db;
if (realAvailability > 0)
{
avail_bus = true;
TextBox2.Text = realAvailability.ToString() + " seats available ";
TextBox2.ForeColor = System.Drawing.ColorTranslator.FromHtml("#008000");
}
else
{
TextBox2.Text = "Seats Not available. Please choose another Stop";
TextBox2.ForeColor = System.Drawing.ColorTranslator.FromHtml("#ff1919");
}
}
}
catch (Exception ex)
{
Response.Write(ex);
}
}
}
protected void Button1_Click1 (object sender, EventArgs e)
{
if (isNotDup)
{
if (avail_bus)
{
// Submit the Form
}
else
{
Label14.Text = "Bus Seats not available!";
Label15.Text = null;
}
}
}
protected void PhoneNumberValidatation (object source, ServerValidateEventArgs args)
{
//some code here
}
}
}
There are three possible solution for this question.
Static - This will create one instance that accessible to all pages (Global).
private static avail_bus = true;
Session State - This enables you to store and retrieve values for a user as the user navigates.
// Get...
private bool avail_bus = (bool)Session["avail_bus"];
// Set
Session["avail_bus"] = true;
Control.ViewState - Gets a dictionary of state information that allows you to save and restore the view state of a server control across multiple requests for the same page.
public bool avail_bus
{
get { return ViewState["avail_bus"] == null ? false : (bool)ViewState["avail_bus"]; }
set { ViewState["avail_bus"] = value; }
}
Every time there is a request for your page, a new instance of that page-class is created to handle that request. So any fields are re-initialized.
You can store a value in ViewState to remember a value over various requests:
namespace eTransport
{
public partial class Appform : System.Web.UI.Page
{
private bool isNotDup
{
set { ViewState["isNotDup "] = value; }
get
{
if (ViewState["isNotDup "] == null)
return true;
return (bool )ViewState["isNotDup "];
}
}
private bool avail_bus
{
set { ViewState["avail_bus"] = value; }
get
{
if (ViewState["avail_bus"] == null)
return true;
return (bool )ViewState["avail_bus"];
}
}
private int max_capacity_bus
{
set { ViewState["max_capacity_bus "] = value; }
get
{
if (ViewState["max_capacity_bus "] == null)
return 0;
return (int)ViewState["max_capacity_bus "];
}
}
private int realAvailability
{
set { ViewState["realAvailability"] = value; }
get
{
if (ViewState["realAvailability"] == null)
return 0;
return (int)ViewState["realAvailability"];
}
}
protected void Page_Load (object sender, EventArgs e)
{
if (!this.IsPostBack)
{
BindDropDown();
}
}
//Method called when dropdown is selected in Bus Stop. It helps to populate Bus Number
protected void DropDownList4_SelectedIndexChanged (object sender, EventArgs e)
{
AutoPopulateBusStop();
Availability();
}
//Method to load drop down values in Bus Stop. These are populated from database
protected void BindDropDown ()
{
//some code here
}
//Method to autopopulate Bus Number based on selection of Bus Stop. The mapping is in the database in the table named -> dropdownlist
protected void AutoPopulateBusStop ()
{
//some code here
}
protected void Availability ()
{
string constr5 = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
using (SqlConnection con5 = new SqlConnection(constr5))
{
try
{
using (SqlCommand cmd5 = new SqlCommand("select count(*) from etms where BusNo='" + TextBox6.Text.ToString() + "'"))
{
cmd5.CommandType = CommandType.Text;
cmd5.Connection = con5;
con5.Open();
int capacity_from_db = Convert.ToInt16(cmd5.ExecuteScalar());
realAvailability = max_capacity_bus - capacity_from_db;
if (realAvailability > 0)
{
avail_bus = true;
TextBox2.Text = realAvailability.ToString() + " seats available ";
TextBox2.ForeColor = System.Drawing.ColorTranslator.FromHtml("#008000");
}
else
{
TextBox2.Text = "Seats Not available. Please choose another Stop";
TextBox2.ForeColor = System.Drawing.ColorTranslator.FromHtml("#ff1919");
}
}
}
catch (Exception ex)
{
Response.Write(ex);
}
}
}
protected void Button1_Click1 (object sender, EventArgs e)
{
if (isNotDup)
{
if (avail_bus)
{
// Submit the Form
}
else
{
Label14.Text = "Bus Seats not available!";
Label15.Text = null;
}
}
}
protected void PhoneNumberValidatation (object source, ServerValidateEventArgs args)
{
//some code here
}
}
}
You can store the availability status in a hidden input field which later gets posted on Button1 click event.
And in button1 click event instead of accessing the avail value from variable access it from hiddenField's value
Another option would be calling Availability() again in click event of button1 as a first line so that it sets proper value in the avail_bus variable
The follwing code works well working for lvwResult, but how can I display the results in listbox1?
I just want to use listbox1 only, instead of lvwResult.
private void btnBrowse_Click(object sender, System.EventArgs e)
{
folderBrowserDialog1.ShowDialog();
if (folderBrowserDialog1.SelectedPath != "")
{
txtDirectory.Text = folderBrowserDialog1.SelectedPath;
}
}
private void btnClose_Click(object sender, System.EventArgs e)
{
this.Close ();
}
private void btnSearchNow_Click(object sender, System.EventArgs e)
{
MLSecurityFinder lSecFinder = new MLSecurityFinderClass ();
int iCounter = 0;
lvwResult.Items.Clear ();
lSecFinder.bScanSubDirectories = chkSubfolders.Checked;
try
{
lSecFinder.FindSecurity (txtSymbol.Text, txtDirectory.Text);
while (lSecFinder.bSecLeft)
{
ListViewItem lItem = lvwResult.Items.Insert (iCounter, lSecFinder.SecName);
lItem.SubItems.Add (lSecFinder.SecSymbol);
lItem.SubItems.Add (lSecFinder.SecFileName);
lSecFinder.FindNextSecurity();
iCounter++;
}
}
catch (System.Runtime.InteropServices.COMException ComEx)
{
//MessageBox.Show (ComEx.Message);
}
finally
{
lSecFinder.DestroySearchDialog ();
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
List boxes don't support multiple columns, unless you're planning on owner-drawing your listbox items. So you'll need to start by deciding how you're going to map your old multi-column data to a single string. Let's say, for the sake of argument, that you decide to combine the used-to-be-columns with commas, so that each of your listbox items would look like "SecName,SecSymbol,SecFileName".
That's the only part that's likely to be at all mysterious. From here, it's just like solving any other problem. You want to replace usages of lvwResult with usages of listbox1? Sounds like a job for search-and-replace to me. Then fix whatever doesn't compile. The code that builds your columns (SubItems) definitely won't compile, but by this point, you will have already decided what to do with that, so it's just a matter of writing code.
Here is just a sample on adding items to the listbox.
public class SampleData {
public string Name { get; set; }
public int Id { get; set; }
}
Now you have the code of:
List<SampleData> sampleList = new List<SampleData>() {
new SampleData() { Id = 1, Name = "Peyton" }
};
listBox1.DataSource = sampleList;
listBox1.DisplayMember = "Name";
Or you can have it directly using the items property.
listBox1.Items.Add(new SampleData() { Id = 1, Name = "Sample" });
listBox1.DisplayMember = "Name";