winforms 根据行计数自动调整UserControl中DataGridView的大小

4dbbbstv  于 2023-06-24  发布在  其他
关注(0)|答案(1)|浏览(127)

我创建了一个包含一些标题标签和一个datagridview的用户控件。根据SQL查询返回的行数,我将这个用户控件插入到form1中n次。每个数据网格中的行数也由另一个SQL查询确定。我想自动调整用户控件(以及它们内部的数据网格视图)的大小,以匹配每个数据网格视图中的行数,这样当我将它们添加到窗体上时,它们会相应地间隔开,并且可以查看所有数据,而不会使每个用户控件之间的间隙过大或过小。
下面是我尝试的结果和屏幕截图,目前似乎没有适当的大小。我不能分享SQL查询,但我可以告诉你,从调试,w和q变量都按预期填充。

int w = distinctValues.Rows.Count;
        int y = 100;
        for (int i = 0; i < w; i++)
        {
            String value = distinctValues.Rows[i].ItemArray[0].ToString();
            SqlDataAdapter adapter2 = new SqlDataAdapter(SQL QUERY HERE, CANT SHARE DUE TO CONFIDENTIALITY);
            DataTable datatable2 = new DataTable();
            adapter2.Fill(datatable2);
            int q = datatable2.Rows.Count;
                var UC = new UCEPMS();
                UC.Name = "UC1" + i;
                UC.Width = 2480;
            UC.Height = (42 * q) + 20;
            UC.Location = new System.Drawing.Point(4, y);
                panel1.Controls.Add(UC);
                UC.Show();
                int UCAnchor = UC.Bottom;
                y = UCAnchor+ 20;
            datatable2.Rows.Clear();
        }

Here is my bad result. On some examples where the rowcount is much higher, the gap is much greater, which makes sense given my code. I know I am not taking the right approach, but am unclear on how to achieve my desired visual.

enyaitl3

enyaitl31#

除了按照@ RandRandRandom的建议使用flowLayoutPanel之外,我还发现了潜在的问题。我没有相应地设置dataGridView的高度,只设置了用户控件的高度。我将代码修改为:

int w = distinctValues.Rows.Count;
    int y = 100;
    for (int i = 0; i < w; i++)
    {
        String value = distinctValues.Rows[i].ItemArray[0].ToString();
        SqlDataAdapter adapter2 = new SqlDataAdapter(SQL QUERY HERE, CANT SHARE DUE TO CONFIDENTIALITY);
        DataTable datatable2 = new DataTable();
        adapter2.Fill(datatable2);
        int q = datatable2.Rows.Count;
            var UC = new UCEPMS();
            UC.Name = "UC1" + i;
            UC.Width = 2480;
        UC.Height = (42 * q) + 20;
        UC.dgvHeight = UC.Height - 20;
        UC.Location = new System.Drawing.Point(4, y);
            panel1.Controls.Add(UC);
            UC.Show();
            int UCAnchor = UC.Bottom;
            y = UCAnchor+ 20;
        datatable2.Rows.Clear();
    }

在我的用户控制中:

public int dgvHeight
        {
        get
        {
            return dataGridView1.Height;
        }
        set
        {
            dataGridView1.Height = value;
        }
    
        }

相关问题