Adjust ListView columns to fit with WinForms

后端 未结 5 1648
不知归路
不知归路 2021-02-07 21:50

I have face resize problem of listview columns. If you anchor/docking the listview to normal winform than the listview anchor or docking works well. I mean lis

5条回答
  •  不知归路
    2021-02-07 22:46

    1. Programatic one. You'll have to maintain it in code.
    2. You can adjust last column size in your listview so that it would be automatically resized. Net sample:

    In a ListView control, with the View property set to Details, you can create a multi-column output. Sometimes you will want the last column of the ListView to size itself to take up all remaining space. You can do this by setting the column width to the magic value -2.

    In the following example, the name of the ListView control is lvSample:

    [c#]
    private void Form1_Load(object sender, System.EventArgs e)
    {
        SizeLastColumn(lvSample);
    }
    
    private void listView1_Resize(object sender, System.EventArgs e)
    {
        SizeLastColumn((ListView) sender);
    }
    
    private void SizeLastColumn(ListView lv)
    {
        lv.Columns[lv.Columns.Count - 1].Width = -2;
    }
    

    EDIT:

    Programaticaly you can do that with own implemented algorithm. The problem is that the list view does not know what of the columns you would like to resize and what not. So you'll have in the resize method (or in resizeEmd method) to specify all the columns size change. So you calculate all the width of the listview then proportionaly divide the value between all columns. Your columns width is multiple to 50. So you have the whole listview width of 15*х (x=50 in default state. I calculated 15 value based on number of your columns and their width) conventional units. When the form is resized, you can calculate new x = ListView.Width/15 and then set each column width to needed value, so

    private void SizeLastColumn(ListView lv)
    {
     int x = lv.Width/15 == 0 ? 1 : lv.Width/15;
     lv.Columns[0].Width = x*2; 
     lv.Columns[1].Width = x;
     lv.Columns[2].Width = x*2;
     lv.Columns[3].Width = x*6;
     lv.Columns[4].Width = x*2;
     lv.Columns[5].Width = x*2;
    }
    

提交回复
热议问题