[英]Selected row (object) in dataGridView C#
我有 class
public class Students
{
public int StudentsID { get; set; }
public string name{ get; set; }
}
我使用了一個對象列表。 然后我從文件中添加對象並在 datagridview 中顯示這個列表,如下所示:
List<Students> listStudents = new List<Students>();
for (int i = 0; i < listStudents.Count; i++)
{
dataGridView2.Rows.Add(listStudents[i].name, listStudents[i].StudentsID);
}
現在是問題所在。 我怎么知道選擇了哪個 object。 我試過這個,但它不起作用 - currentObject 是 null
private void btn_Click(object sender, EventArgs e)
{
Students currentObject = (Students)dataGridView1.CurrentRow.DataBoundItem;
}
刪除此代碼:
for (int i = 0; i < listStudents.Count; i++)
{
dataGridView2.Rows.Add(listStudents[i].name, listStudents[i].StudentsID);
}
將您的列表添加到 Datagridview 數據源:
dataGridView2.DataSource = listStudents;
獲取當前行為 object:
Students currentObject = (Students)dataGridView2.CurrentRow.DataBoundItem;
不熟悉使用 Winforms 和 DataGridViews 的人傾向於自己添加 DataGridView 的行。
但是有一個更簡單的方法:使用 DataGridView 的DataSource
。
您計划在 DataGridView 中顯示Students
。 您可能會有兩列,一列顯示 StudentId,另一列顯示名稱。
每個 DataGridViewColumn 都有一個字符串屬性DataGridViewColumn.dataPropertyName此屬性包含此列應顯示的屬性的名稱。
因此,要顯示 ID 和名稱,您需要以下內容:
columnStudentId.DataPropertyName = nameof(Student.StudentId);
columnStudentName.DataPropertyName = nameof(Student.Name);
您可能會使用 Visual Studio 設計器設置這些屬性。
現在要顯示學生,每行一個學生,您所要做的就是將集合分配給 DataGridView 的 DataSource:
List<Student> students = ...
this.DataGridView1.DataSource = students;
和賓果游戲,每個學生的名字和 id 都顯示在 DataGridView 中。
解決方案是一次性的:不記錄更改。 如果您希望表中的更改自動更新,請將項目放入BindingList<Student>
:
private BindlingList<Student> students;
private void DisplayStudents(IEnumerable<Student> students)
{
this.students = new BindingList<Student>(students.ToList());
this.dataGridView1.DataSource = this.students;
}
操作員所做的任何更改都會在this.students
中自動更新,您對this.Students
所做的任何更改都會自動顯示。
private void AddOrUpdateStudent(Student studentToUpdate)
{
// Is there already a Student with this Id shown?
var existingStudent = this.Students
.Where(student => student.StudentId == studentToUpdate.StudentId)
.FirstOrDefault();
if (existingStudent != null)
{
// Student exists, update the name:
existingStudent.Name == studentToUpdate.Name;
}
else
{
// Student does not exist yet; add it:
this.Students.Add(studentToUpdate);
}
}
數據網格視圖會自動更新。
同樣反過來:操作員編輯 datagridview 中的一個或多個單元格並按下按鈕:
private void OnButtonOk_Clicked(object sender, ...)
{
// all edited cells are already updated in this.Students:
this.ProcessStudents(this.Students);
}
要獲取在某一行中顯示的學生,可以使用屬性DataGridViewRow.DataBoundItem
IEnumerable<Student> selectedStudents = this.dataGridView1.SelectedRows
.Cast<DataGridViewRow>()
.Select(row => (Student)row.DataBoundItem);
只需這樣做:
List<Students> listStudents = new List<Students>();
...
dataGridView2.DataSource = listStudents;
並擺脫“for”循環。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.