我的表格标识的数据网格视图,最后一列有状态。
因此,我假设我在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);
}
}
}
答案 0 :(得分:1)
您可能想要循环播放 dataGridView1.SelectedRows获取每个DataGridViewRow对象 代码:
foreach(DataGridViewRow row in dataGridView1.SelectedRows)
{
// implement your logic here
// update selected rows by making changes to 'row' object
}
答案 1 :(得分:1)
执行此操作的正确方法是使用DataBinding。由于您使用的是诸如“识别”之类的域对象,因此这将是一个合适的选择。
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));
}
}
}