增加列表框中的行间距

时间:2018-05-23 20:12:16

标签: c# listbox

如何增加listbox1中的行间距? Error; Error2  listbox1

以及水平缩进每个字符串。并且listbox1中所选项目的颜色为红色。 |||||||||||||||||||||||||||||||||||||||||||||||||| |||||||||||||||||||||||||||||||||||||||||||||||||| |||||||||||||||||||||||||||||||||||||||||||||||||| ||||||||||||||||

"Form1"

    public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        if (Properties.Settings.Default.Accounts == null)
            Properties.Settings.Default.Accounts = new List<Account>();

        if (Properties.Settings.Default.Accounts != null)
        {
            foreach (var account in Properties.Settings.Default.Accounts)
            {
                listBox1.Items.Add(account);
            }
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        new Form2(listBox1).Show();
    }

    private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (listBox1.SelectedItem is Account selectedAccount)
        {
            textBox1.Text = selectedAccount.Name;
            textBox2.Text = selectedAccount.Login;
            textBox3.Text = selectedAccount.Password;
        }
    }

    private void button2_Click(object sender, EventArgs e)
    {
        if (Properties.Settings.Default.Accounts != null)
            Properties.Settings.Default.Accounts.RemoveAt(listBox1.SelectedIndex);

        listBox1.Items.Remove(listBox1.SelectedItem);

        Properties.Settings.Default.Save();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        listBox1.ItemFormatStyle.Margin = new Padding(5, 10, 2, 2);
    }
}

"Form2"

public partial class Form2 : Form
{
    private readonly ListBox _listBox;

    public Form2(ListBox listBox)
    {
        InitializeComponent();
        _listBox = listBox;
    }

    private void button1_Click(object sender, System.EventArgs e)
    {
        Account account = new Account
        {
            Name = textBox1.Text,
            Login = textBox2.Text,
            Password = textBox3.Text
        };

        _listBox.Items.Add(account);

        Properties.Settings.Default.Accounts.Add(account);

        Properties.Settings.Default.Save();

        Close();
    }
}

Class "Account";

public class Account
{
    public string Name { get; set; }

    public string Login { get; set; }

    public string Password { get; set; }

    public override string ToString()
    {
        return $"{Name}";
    }
}

1 个答案:

答案 0 :(得分:1)

https://www.lidorsystems.com/support/articles/winforms/listbox/space-between-items.aspx

这包含了你要求的所有3件事。

间距:

listBox1.ItemSpacing = 10;

水平缩进每个字符串:

listBox1.ItemFormatStyle.Margin = new Padding(5, 10, 2, 2);

listBox1.ItemFormatStyle.Padding = new Padding(7);

以下是更改颜色的方法:

How to change ListBox selection background color?