简体   繁体   English

在datagridview c#中使用计数器的问题

[英]Issue using counters in datagridview c#

I have datagridview table. 我有datagridview表。 Whenever a user selects row and click 'Update Counter' button, counter value changes to 1 at top corner of window. 每当用户选择行并单击“更新计数器”按钮时,计数器值将在窗口的上角变为1。

Now if a user selects the same row, the counter is updated incrementally which I don't want. 现在,如果用户选择同一行,则计数器将逐步递增,这是我所不希望的。 I don't want counter to update on same row selection. 我不希望计数器在同一行选择上进行更新。

My code - 我的代码-

Int32 selectedRowCount = dataGridView1.Rows.GetRowCount(DataGridViewElementStates.Selected);                       

for (int i = 0; i < selectedRowCount; i++)
{                 
  // need to insert condition so that counter is not updated when same row is selected again.
 Counter.Text = Convert.ToString(i + 1);
                    }
}

I new to C# development, please provide changes. 我是C#开发的新手,请提供更改。

Without seeing the rest of the code, or really understanding what you are doing (is this list going to change, what is the counter, can you identify the selected row easily?), all I can really suggest is maintaining a list of selected rows and checking that before updating the counter. 在没有看到其余代码的情况下,或者没有真正了解您在做什么(此列表是否会更改,计数器是什么,您可以轻松识别所选行吗?),我真正建议您维护的是所选行的列表并在更新计数器之前进行检查。

For example, in the for each: 例如,在中的每个:

if (selectedRows.Contains(rowIdentifier)) continue;//if you want to keep looping, otherwise break;

You may use the Tag property of the DataGridViewRow to identify rows already selected. 您可以使用DataGridViewRow的Tag属性来标识已经选择的行。

foreach (DataGridViewRow r in dataGridView1.SelectedRows)
  if (r.Tag!=null) { Counter.Text=int.Parse(Counter.Text)+1 ; r.Tag=True ; } 

I would add a condition statement that checks to see if the variable is dirty or has already been updated. 我将添加一个条件语句,以检查该变量是否为脏变量或已被更新。 This sounds similar to a concurrency issue or checking concurrency, I'm sure if you searched for ways to resolve concurrency issues the logic used would be similar. 这听起来类似于并发问题或检查并发,我敢肯定,如果您正在寻找解决并发问题的方法,则所使用的逻辑将是相似的。 I agree with @johnc 我同意@johnc

I would utilize the onclick event then disable the ability to click the same row again. 我会利用onclick事件,然后禁用再次单击同一行的功能。

OR use some other unique property of the row and check against it. 或使用该行的其他一些独特属性并对其进行检查。

if(row.uniqueProperty == -1)
{

    Counter.Text = Convert.ToString(i + 1);
}

Basically, I created a SQL table storing all values from selected row. 基本上,我创建了一个SQL表,用于存储所选行中的所有值。 If selected row value is something already there in the table, the counter doesn't get updated while the counter gets updated when unique row is selected. 如果所选行的值已存在于表中,则当选择唯一行时,计数器不会更新,而计数器会更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM