Access to form controls in classes
I'm new to C# programming, and I have a simple question. Let's say I have a form that contains several controls, perhaps a couple of text boxes and a combo box. Next, I have a class that contains methods to 'do something' with the controls on the form. Is this possible, and if so, how do I referrence the controls from the class?
Sam HobbsPosted Aug 25, 2010, 3:34 PM
Manikavelu VelayuthamPosted Aug 25, 2010, 12:40 PM
public DataTable CmbItems()
{
string cSQLSelect = @"SELECT * FROM MyTable";
SqlConnection cn = new SqlConnection(GetConnString()); *** this method not included for clarity
SqlDataAdapter da = new SqlDataAdapter(cSQLSelect, cn);
DataSet ds = new DataSet();
da.Fill(ds, "Table");
DataTable dt = ds.Tables["Table"];
return dt;
}
next you need to call this function in your form....for example you mentioned the class name as MyData.
MyData objData = new MyData();
DataTable dt = objData.cmbItems();
foreach (DataRow dr in dt.Rows)
{
cmbMyComboBox.items.add(...)
}
Like that you can continue.
If this post really helped you, please mark it as accepted answer.
RonPosted Aug 25, 2010, 10:30 AM
Manikavelu - Perhaps I should explain in greater detail the problem I'm trying to solve. I have a combo box on a form and I'd like to add/update the items from a table. To do this I've written a class method:
class MyData
{
private void CmbItems()
{
string cSQLSelect = @"SELECT * FROM MyTable";
SqlConnection cn = new SqlConnection(GetConnString()); *** this method not included for clarity
SqlDataAdapter da = new SqlDataAdapter(cSQLSelect, cn);
DataSet ds = new DataSet();
da.Fill(ds, "Table");
DataTable dt = ds.Tables["Table"];
foreach (DataRow dr in dt.Rows)
{
cmbMyComboBox.items.add(...)
}
This is where I was hoping to have access to the combo box. The control is unknown to Intellisense, and therefore is not available to my class code. I've tried changing the combo box from private to public, but that did not work either. What am I doing wrong?
RonPosted Aug 25, 2010, 9:40 AM
Manikavelu VelayuthamPosted Aug 25, 2010, 2:03 AM
public string Category {
get {
return textbox1.Text;
}
set {
textbox1.Text= value;
}
}