Populating data in dropdown menu - c#

I am new to c# so bit stuck at what I thought was a very simple module. I just need to display data in the dropdown menu but getting some error while binding... or I will say even before binding. Here is what I am trying to do..I am really sorry if I am doing a very simple mistake but I tried my best & now I think I need some guidance..
CustomService.cs
public partial class CustomService
{
public List<Code> GetDepartment(bool activeOnly)
{
List<Code> retVal = new List<Code>();
---some code----
return retVal;
}
}
ProgramList.ascx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
List<Code> dept = new List<Code>CustomService.GetDepartment(true);
ddlDepartment.DataSource = dept;
ddlDepartment.DataBind();
}
}
//error an object reference is required for an nonstatic field, method or Property CustomService.GetDepartment(true);

you forgot to create object first and than you can call the method
another thing is you just need to assign the value directly as i did below, there is no need to create any new list
check the code below that will work for you
CustomService custsrv = new CustomService();
List<Code> dept = custsrv.GetDepartment(true);

To be able to call the method GetDepartment, you need to have a new instance of CustomService created:
CustomService service = new CustomService();
service.GetDepartment(true);
or to make the method static:
public static List<Code> GetDepartment(bool activeOnly) { }
However, if you put it static, every variables used by that method that reside inside the class will also need to be static.

I think this would help.
CustomService custS = new CustomService();
ddlDepartment.DataSource = custS.GetDepartment(true);
ddlDepartment.DataBind();

Related

How to properly declare class variables (CUIT Controls)

I am setting up Coded UI Tests for WPF application and I want to use code approach instead of record-and-generate-code approach. I'd like to use page objects trough code and I need to declare control (buttons, tabs, etc.) variables in page objects that would be used by multiple functions.
I tried declaring the variable in a class and adding properties in constructor (pendingButton1)
and creating function which returns the control and assigning to a variable in a class (pendingButton2) but neither worked.
It works when I declare the variable (or create the variable by function) within the function that I want to use the variable in (pendingButton3 and 4).
public partial class Press : Header
{
WpfToggleButton pendingButton1 = new WpfToggleButton(_wpfWindow);
WpfToggleButton pendingButton2 = Controls.Press.getPendingButton(_wpfWindow);
public Press(WpfWindow wpfWindow):base(wpfWindow)
{
this.pendingButton1.SearchProperties[WpfControl.PropertyNames.AutomationId] = "Tab1Button";
}
public void clickPendingButton() {
WpfToggleButton pendingButton3 = new WpfToggleButton(_wpfWindow);
pendingButton3.SearchProperties[WpfControl.PropertyNames.AutomationId] = "Tab1Button";
WpfToggleButton pendingButton4 = Controls.Press.getPendingButton(_wpfWindow);
Mouse.Click(pendingButton1); //UITestControlNotFoundException
Mouse.Click(pendingButton2); //UITestControlNotFoundException
Mouse.Click(pendingButton3); //This works
Mouse.Click(pendingButton4); //This works
}
}
I'd like to make it work when I declare the pendingButton outside clickPendingButton() function since it is used in multiple other functions.
The helper function Controls.getWpfButton() return just properties of the button, not "real" button. It has to be used in a constructor, then it can be used anywhere within the class. I wouldn't say its best practice but it works for me.
Press.cs
public partial class Press : SharedElements
{
private WpfButton pendingButton;
public Press(WpfWindow wpfWindow):base(wpfWindow)
{
pendingTab = Controls.getWpfButton(_wpfWindow, "Tab1Button");
}
public void clickPendingButton() {
Mouse.Click(pendingButton);
}
}
Controls.cs
internal static WpfButton getWpfButton(WpfWindow wpfWindow, string AutomationId)
{
WpfButton button = new WpfButton(wpfWindow);
button.SearchProperties[WpfControl.PropertyNames.AutomationId] = AutomationId;
return button;
}
What you want appears to be exactly the sort f code that the Coded UI record and generate tool generates. It creates many pieces of code that have a structure of the following style:
public WpfToggleButton PendingButton
{
get
{
if ((this.mPendingButton == null))
{
this.mPendingButton = new WpfToggleButton( ... as needed ...);
this.mPendingButton.SearchProperties[ ... as needed ...] = ... as needed ...;
}
return this.mPendingButton;
}
}
private WpfToggleButton mPendingButton;
This code declares the button as the class property PendingButton with a private supporting field that has an initial and default value of null. The first time that property is needed the get code executes the required search and saves the found control in the private field. That value is then returned in each subsequent usage of the property. Note that assigning null to the supporting field can be done to cause a new search, as demonstrated in this Q&A.

How to access array defined in class in another class without constructor?

I have this code given by the API that I'm using.
public partial class getMerchant : object, System.ComponentModel.INotifyPropertyChanged
{
private int[] iMerchantIdField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("iMerchantId", Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 0)]
public int[] iMerchantId
{
get
{
return this.iMerchantIdField;
}
set
{
this.iMerchantIdField = value;
this.RaisePropertyChanged("iMerchantId");
}
}
}
Now I was trying to create an object of this class and to run it:
private void btnShowResult_Click(object sender, EventArgs e)
{
Awin.ApiPortTypeClient client = new Awin.ApiPortTypeClient();
UserAuthentication userAuthentication = new UserAuthentication();
userAuthentication.sApiKey = "111";
getMerchant merchant = new getMerchant();
merchant.iMerchantId[0] = 2518;
merchant.iMerchantId[1] = 3030;
var response = client.getMerchant(userAuthentication, merchant);
lblResult.Text = response[0].sName.ToString();
}
But whenever I try to run it it gives a nullreferenceexception when the compiler hit the line merchant.iMerchantId[0] = 2518;
What I understood so far is that this iMerchantId[] hasn't been declared yet. But the problem is also that I can't find an answer how to declare it.
I am thankful for any help that I can get.
To solve this initialize the backup property with required indices, which means the property definition would be like this:
private int[] iMerchantIdField= new int[2];
Need not to change the Public property, try using the current code, it will works fine without previous errors, since the bounds of the arrays are defined and initialized now through these backup properties.
Additional notes : If you deals with a List instead for an array, then you have to instantiate the list through the backup property, otherwise NullException will thrown. In such case the declaration would be :
private List<int> iMerchantIdField= new List<int>();

Able to set value of private variable by public property without setter

How is this code able to compile and run error free?
private void queueToolStripMenuItem_Click(object sender, EventArgs e)
{
//Class name MDPlayer
Playlist.QueueList.Add(tempPlayList[songView.SelectedIndex]);
Playlist.GetQueue = null;
QueueCombobox.Items.Clear();
foreach (PlayListData pld in Playlist.QueueList)
{
QueueCombobox.Items.Add(pld.Track);
}
}
class Playlist
{
private static List<PlayListData> queueList = new List<PlayListData>();
public static List<PlayListData> QueueList
{
get { return queueList;}
}
}
How am I able to add to queueList that is private through the public property QueueList that doesn't even have a setter?
You are able to call methods on the return value of a property getter.
Your property getter returns a List<>. List<> defines the Add method. Thus you can call the Add method on the List<> that you asked for.
Note that you can not assign a new value to the listQueue from outside the PlayList class because it is private.
Also, you can not assign a new value to the ListQueue property because it has no setter accessor.
This will fail: PlayList.QueueList = new List<PlayListData>();
Because you're adding to the list via the getter. You're not setting the underlying private variable to anything. You can do QueueList.Add(), but not QueueList = newList.
When you get a value from the getter, it returns the whole class and that class is alterable. You only need a setter when you want to set the whole variable to an entirely different class.
Summary
You only need to use a setter when setting the whole variable.
Can
Playlist.QueueList.Add(tempPlayList[songView.SelectedIndex]);
Cannot
Playlist.QueueList = new List<PlayListData>();

Is it safe to make a List public for using it as a DataGridView's datasource?

i am creating a C# class library that reads data from a socket and store some data in a list. This list will change more the once per second during execution time.
In need this list to be the content of a dataGridView of a winforms application, but i'm wondering how can i expose it out of my library.
Is it safe to declare the List as public in the classLibrary like:
public class THRManager
{
public List <GaugeItem> outSource;
...
and then on the WinForm side:
public TMRMainForm()
{
THRManager thrC = new THRManager();
dataGridView1.DataSource = thrC.outSource;
...
Is this safe? If not, what's the best way?
Thx!
==================EDIT
Should i use DataTable or BindingSource ?
Use a ReadOnlyCollection but create it once in your constructor or where ever else you need them, in order not to do new ReadOnlyCollection... every time you access it.
public class THRManager
{
private List<GaugeItem> outsource;
private ReadOnlyCollection<GaugeItem> outSourceReadOnly;
public THRManager()
{
outSource = new List<GaugeItem>();
outSourceReadOnly = new ReadOnlyCollection<GaugeItem>(outSource);
}
public ReadOnlyCollection<GaugeItem> OutSource
{
get { return outSourceReadOnly; }
}
}
Hope code works without syntax errors :)
This is a safer option when publishing an inner collection.
private List<GaugeItem> outSource;
public ReadOnlyCollection<GaugeItem> OutSource
{
get { return new ReadOnlyCollection<GaugeItem>(outSource); }
}

Public variable invoking incorrect result

public partial class ThanglishToTamilGUI : Form
{
public string anz;
public ThanglishToTamilGUI()
{
InitializeComponent();
}
public void btnConvertToBraille_Click(object sender, EventArgs e)
{
anz = richTextBoxTamil.Text.ToString();
GUI.TamilToBrailleGUI c1 = new GUI.TamilToBrailleGUI();
c1.Visible = true;
}
}
I need to pass my richtextbox (richTextBoxTamil) content to variable call anz.
I am retrriving anz variable in other form as form load event:
private void TamilToBrailleGUI_Load(object sender, EventArgs e)
{
ThanglishToTamilGUI tt = new ThanglishToTamilGUI();
String apper = tt.anz;
richTextBoxTamil.Text = apper;
}
My Problem:
I am getting null values as result. Since if I assigned any values that invoked correctly.
public partial class ThanglishToTamilGUI : Form
{
public string anz = "Hai";
public ThanglishToTamilGUI()
{
InitializeComponent();
} ...
Here my ans value is passed as "Hai". But my requirement is to get what ever the content in the richTextBoxTamil and pass it to that public variable call anz. What went wrong here please help me.
Thank you.
This is the problem:
ThanglishToTamilGUI tt = new ThanglishToTamilGUI();
String apper = tt.anz;
How do you expect apper to ever be anything other than null? You're fetching the variable from a freshly-created form, which has never been shown, and which has never had btnConvertToBraille_Click called on it.
Presumably there's an existing ThanglishToTamilGUI object somewhere, and that's the one you want to fetch the variable from. Basically, one form needs to know about the instance of the other form.
(I'd also strongly suggest using a property rather than a public variable, but that's a different matter. You might not even need to have a separate variable at all - just declare a property which fetches richTextBoxTamil.Text.)
Alternatively, just pass the relevant string to the constructor of the new form:
public void btnConvertToBraille_Click(object sender, EventArgs e)
{
GUI.TamilToBrailleGUI c1 = new GUI.TamilToBrailleGUI(richTextBoxTamil.Text);
c1.Visible = true;
}
Then the new form doesn't need to know about the old form at all - it only needs to know the text to display.
(You might want to pull it out of the constructor and into a settable property, but it's the same basically principle: the code creating the form pushes the data, rather than the new form pulling it.)
You can create a public property to access the current Text value of the textbox.
public string RichTextBoxText
{
get
{
return richTextBoxTamil.Text;
}
}
The way you do it now the form is instantiated, but the click event is not fired. So there's no way you will get anything other than what you initialized the field to.
Load is not the place to look for user input. An event (like click) is where you need to check the property value:
private void SomeClick(object sender, EventArgs e)
{
String result = thanglishToTamilGUIObject.RichTextBoxText;
//do something with text
}

Categories