只有Datagrid上的SelectedRows会受到影响

本文关键字:受到影响 SelectedRows 上的 Datagrid 只有 | 更新日期: 2023-09-27 18:04:27

我有一个datagridview用于我的表标识,在最后一列上有一个Status。

假设我在datagridview的10行中选择了5行。

我想做的是,当我点击一个按钮,只有选定的行会受到影响,他们的状态将被改变。

我试过这个代码和其他代码,似乎没有一个工作。我是c#新手,有人能帮我吗?

private void button_Click(object sender, EventArgs e)
    {
        int count = dataGridView1.SelectedRows.Count;
        for (int i = count-1; i >=0; i--)
        {
            if (i == dataGridView1.SelectedRows.Count)
            {
                Identification it = new Identification();
                it.Status = "ACTIVE";
                Repository.Identification_UpdateStatus(it);
            }
        }
    }

只有Datagrid上的SelectedRows会受到影响

您可能需要循环执行dataGridView1。SelectedRows获取每个DataGridViewRow对象代码:

foreach(DataGridViewRow row in dataGridView1.SelectedRows)
{
   // implement your logic here
   // update selected rows by making changes to 'row'  object
}

正确的方法是使用数据绑定。因为你正在使用领域对象,如"标识",这将是一个合适的适合这里。

 public partial class Form1 : Form
{
    //Your form
    public Form1()
    {
        InitializeComponent();
        //Wrap your objects in a binding list before setting it as the 
        //datasource of your datagrid
        BindingList<Identification> ids = new BindingList<Identification>
        {
            new Identification() { status="NEW"  },
             new Identification() { status="NEW"  },
              new Identification() {status="NEW"  },
        };
        dataGridView1.DataSource = ids;
    }
    private void btnChangeStatus_Click(object sender, EventArgs e)
    {   //Where the actual status changing takes place
        foreach (DataGridViewRow row in dataGridView1.SelectedRows)
        {
            var identifaction = row.DataBoundItem as Identification;
            identifaction.status = "VERIFIED";
        }
    }
    //Model: Class that carries your data
    class Identification: INotifyPropertyChanged
    {
        private string _status;
        public string status
        {
            get { return _status; }
            set
            {
                _status = value;
                NotifyPropertyChanged("status");
            }
        }
        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(string name)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(name));
        }
    }    
}