开发者

How to Stop DataGrid on Adding Rows?

This is my Method:

Datatable data2 = new Datatable();
int result = 0;
using (SqlConnection conn = new SqlConnection(connStr))
{
    try
    {
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = conn;
        conn.Open();
        cmd.CommandText = "SELECT * from TableA";
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        result = da.Fill(data2);

        if (result > 0)
        {
            this.dgBatch.DataSource = data2;
        }
        else
        {
            MessageBox.Show("No Records!");
        }
    }
    catch (Exception ee)
    {
        MessageBox.Show(ee.Message);
    }
    finally
  开发者_运维问答  {
        if (conn.State == ConnectionState.Open) conn.Close();
    }
}

If I call this Method consecutively it always Add Rows from the first Query.

Ex:

  Table Data: 5

  First Call: 5

  Second Call: 10. It duplicates all Records from first Call.

Thanks in Regards


That is because you are reusing data2. You should create a new instance for data2 before the following line:

result = da.Fill(data2);


Assuming data2 is a datatable

result = da.Fill(data2); will always merge the results because you are using same instance of datatable.

if you want to get every time a fresh copy than create a new instance of datatable and than fill this instance with data.

so the line before result = da.Fill(data2); add following line.

data2 = new Datatable();

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜