如何在表单中使用类对象 [英] How Do I Use Class For Ojects In A Form

查看:52
本文介绍了如何在表单中使用类对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亲爱的所有人,



我有多种形式,有多种形式的常见组合框对象,其中包含会话/财政年度。我现在正在做的是一次又一次地为组合对象编写相同的代码。



现在,我需要的是一个我只编写代码的类可以通过参考该课程访问任何表格上的组合框。



我不知道怎么做...



我做过的努力:GOOGLE为此而自己尝试创建一个类并在其中编写代码但无法实现目标。



代码:



Dear All,

I had got multi forms with a common combo box object in many forms, which contains session/financial year. What I'm doing right now is writing again and again same code for the combo object.

Now, what I need is a class where I just write the code and can access for combo box on any form by referring to that class.

And I donno how to do that...

efforts I did : GOOGLE for this and tried by myself by creating a class and wrote code in it but couldn't achieve the target.

code:

class financial_session
    {
        connectionString cs = new connectionString();
            
                OleDbConnection database = new OleDbConnection(cs.connString());
                database.Open();

                string queryString = "Select distinct(bc_session) from cm_master order by bc_session desc";

                OleDbCommand cmd = new OleDbCommand(queryString, database);
                OleDbDataReader dr = cmd.ExecuteReader();

                cmbSession.Items.Clear();

                while (dr.Read())
                {
                    cmbSession.Items.Add(dr.GetValue(0).ToString());
                }
                database.Close();

    }

推荐答案

创建一个类并创建一个方法将数据绑定到组合框控件中。



这是绑定组合框控件的示例代码。



Make a class and create a method to bind data into combo box control.

Here is the sample code to bind the combobox control.

public void BindComboBoxDataContext(ComboBox comboBox, DataTable dtDataContext, string displayMemberPath, string selectedValueMemberPath)
        {
            try
            {
                comboBox.DataContext = dtDataContext;
                comboBox.DisplayMemberPath = displayMemberPath;
                comboBox.SelectedValuePath = selectedValueMemberPath;
                comboBox.SelectedIndex = -1;
            }
            catch (Exception ex)
            { LogExceptionDetails(ex); }
        }





每当需要为控件设置数据时,只需为此类创建一个对象并调用此方法。



Whenever required to set the data for the control, just make an object for this class and call this method.


创建一个UserControl,并从ComboBox派生它或在其中嵌入一个ComboBox。

将您的代码添加到该类,并使用下一个控件代替所有形式的原始ComboBox。



它比听起来更容易 - 我一直这样做,即使我只使用控件一次(因为它封装了控制功能,并且显着简化了表单代码)。

MSDN [ ^ ]可以帮助细节。
Create a UserControl, and either derive it from ComboBox or embed a ComboBox in it.
Add your code to that class, and use the next control instead of the "raw" ComboBox in all your forms.

It's easier than it sounds - I do it all the time, even if I will only be using the control once (since it encapsulates the control functions, and simplifies the form code significantly).
MSDN[^] can help with the details.


这篇关于如何在表单中使用类对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆