当我点击c#中的下一个记录按钮时,为什么每次数据表行数都加倍?

时间:2015-11-12 10:11:15

标签: c# sql

我正在开发windows表单应用程序,所以我从表中获取数据   在sql server中并将数据存储在数据表中。

之后我在我的代码中检查了这个条件:

if(dt.Rows.count>0)

然后,

进入循环并为文本框指定值。可以正常使用。

EX:

int count=0;    //Globally

在我的Next_Record函数中:

if(dt.Rows.Count>0)
{
     txtWardId.Text = dt.Rows[count]["id"].ToString();
     count+=1;  
} 

然后我全局定义了一个计数变量然后增加该变量   每次点击(下一个记录按钮),它都会给另一个记录罚款。但是   dt.Rows.count这给出了double值。 (表示行数是7   然后接下来点击行计数为14,第三次单击21 ...就像这样)

这是我的联系:

            SqlDataReader _reader;
            cmd = new SqlCommand();
            cmd.Connection = openConnection();
            cmd.CommandText = Text;     //Assign the SP Name to Command Object
            cmd.CommandType = CmdType;  //Assign the SP Type to Command Object

            _reader = cmd.ExecuteReader();  //Execute the SP 
            dt.Load(_reader);
            _reader.Close();
            return dt;

你能解决这个问题是什么?

感谢。

1 个答案:

答案 0 :(得分:3)

You are adding the rows to the table always when you click on the Next_Record-button. DataTable.Load will merge new rows with existing rows.

You have two options:

  1. Don't load the table on each Next_Record-click, it's not clear why you need it at all.
  2. Clear the table first

    dt.Clear();  // or dt = new DataTable();
    using(var _reader = cmd.ExecuteReader())
        dt.Load(_reader);
    

One thing to note, DataTable.Load merges new rows with existing. But how depends on the LoadOption value passed to Load(default is PreserveChanges). But it can only merge rows when the primary key is defined. Otherwise those rows are never merged and added to the existing table.

Also note that your if condition is not complete:

if(dt.Rows.Count > 0)
{
     txtWardId.Text = dt.Rows[count]["id"].ToString();
     count += 1;  
} 

This fails if count is greater or equal dt.Rows.Count. I would start at record one again:

if(dt.Rows.Count > 0)
{
     if(count >= dt.Rows.Count)
         count = 0;
     txtWardId.Text = dt.Rows[count]["id"].ToString();
     count++;  
}