簡體   English   中英

DataGridView,獲取所選行的第一列的值

[英]DataGridView, Get the value of the first column of the selected row

我想知道哪種最有效的方法來獲取DataGridView行中第一列的值。

目前,我正在使用以下代碼:

List<string> SelectedRows = new List<string>();
foreach (DataGridViewRow r in dgv.SelectedRows)
{
    SelectedRows.Add(r.Cells[0].Value.ToString());
}

int index = Convert.ToInt32(SelectedRows[0]);

這很好用; 但是,有沒有更有效的選擇呢?

“最有效”通常是主觀的。 我不知道以下代碼比您已經擁有的代碼更快或更短,但這是我更喜歡使用的方法。

如果您試圖從特定列中獲取所有值的列表,請嘗試以下操作:

var results = dataGridView1.SelectedRows
                           .Cast<DataGridViewRow>()
                           .Select(x => Convert.ToString(x.Cells[0].Value));

如果一次只允許一個選定的行,並且想要轉換特定的單元格,請嘗試以下操作:

var index = Convert.ToInt32(dataGridView1.CurrentRow.Cells[0].Value);

我用答案中給出的代碼做了一些性能測試。 每種方法的平均時間超過1.000.000倍:

我的原始代碼:

List<string> SelectedRows = new List<string>();
foreach (DataGridViewRow r in dgv.SelectedRows)
{
    SelectedRows.Add(r.Cells[0].Value.ToString());
}

int index = Convert.ToInt32(SelectedRows[0]);

時間= 0,0159毫秒

var results = dataGridView1.SelectedRows
                           .Cast<DataGridViewRow>()
                           .Select(x => Convert.ToString(x.Cells[0].Value));

時間= 0,0152毫秒

var index = Convert.ToInt32(dataGridView1.CurrentRow.Cells[0].Value);

僅當單選時:0,0013438毫秒

List<string> SelectedRows = new List<string>();
for (int count = 0; count < dgv.SelectedRows.Count; count++)
{
    SelectedRows.Add(dgv.SelectedRows[count].Cells[0].Value.ToString());
}
int index = Convert.ToInt32(SelectedRows[0]);

時間= 0,0057毫秒

從Patrick Smacchia的博客中復制以下內容:

The fact that for is more efficient than foreach results from the fact that foreach is using an enumerator object behind the scene.

我更喜歡使用for循環而不是foreach循環,當您不必對每個元素做任何事情時, for循環最好比foreach循環更快,並且只需使用如下索引即可解決您的問題:

List<string> SelectedRows = new List<string>();
for (int count = 0; count < dgv.SelectedRows.Count; count++)
{
    SelectedRows.Add(dgv.SelectedRows[count].Cells[0].Value.ToString());
}
int index = Convert.ToInt32(SelectedRows[0]);

要獲取所選行的第一列的值,請在dataGridView的contentClick中放入此代碼,然后將該值保存在id變量中

  private void datagridview1_CellContentClick(object sender, DataGridViewCellEventArgs e)
            {

             var id = Convert.ToInt32(datagridview1.Rows[e.RowIndex].Cells[0].Value);
            }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM