从另一个非表单类将数据传递到DataGridView表单的最佳方法

时间:2016-08-17 01:26:30

标签: c# winforms datagridview windows-forms-designer

正如标题所说,我需要将一个哈希表列表从常规类传递给要在DataGridView中呈现的表单类。到目前为止我得到的是:

    namespace somenamespace
{
    class aldeloUpdater
    {
        private static string client = "chanchitos";
        private static string establishment = "c1";

        static void Main()
        {
            try
            {
                var guiForm = new GuiForm(); //  Instantiating the Form-derived class.
                string deliveriesListResp = getOrders();

                Processing...
                foreach (...)
                {
                    if ((bool)DBresponse["status"])
                    {
                        guiForm.dataGridViewProducts = (List<Hashtable>)DBresponse["deliveriesSaved"]; // Passing the data to the DataGridView.

                        foreach (Hashtable delivery in (List<Hashtable>)DBresponse["deliveriesSaved"])
                        {
                            string updateDeliveryResponse = updatePedidoInDomicilios(delivery["domiciliosOrderId"].ToString(), 2, DBresponse["errmsg"].ToString()); 
                        }
                    }
                    else
                    {
                        Processing...
                    }
                }
                guiForm.ShowDialog(); // Showing the form.
                More processing...
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception details: " + e.ToString());
                Console.ReadLine();
            }
        }
    More methods...
}

现在Form类看起来像这样:

namespace somenamespace
{
    public partial class GuiForm : Form
    {
        public List<Hashtable> dataGridViewProducts; // Variable used to store the data to be rendered by the DataGridView.

        public GuiForm()
        {
            InitializeComponent();
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void GuiForm_Load(object sender, EventArgs e)
        {
            int index = 0;
            foreach (Hashtable product in dataGridViewProducts)
            {
                dataGridView1.Rows.Add();
                dataGridView1.Rows[index].Cells[0].Value = product["productName"];
                dataGridView1.Rows[index].Cells[1].Value = product["userName"];
                dataGridView1.Rows[index].Cells[2].Value = product["dateAndTime"];
                dataGridView1.Rows[index].Cells[3].Value = product["domiciliosOrderId"];
                index++;
            } 
        }

        Some more methods.

    }
}

现在这段代码运行得很好,数据显示在DataGridView中,但我觉得必须有更好的方法来实现这个目标,这只是我对C#的新手。我将很感激建议,甚至更多的代码草图,说明如何以更好的方式做到这一点。

感谢。

0 个答案:

没有答案