Click here to Skip to main content
15,889,595 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello everyone,

Please someone help me out from this problem. I have an datagridview which is bound to an datasource which contains two tables CompDetails and Orders. Now when i click on button and if texbox.text=1 data will be displayed fine, if i click the button for second time the data will be displayed again. I mean i have 4 rows in table, when i click button second time the extra 4 rows will be displayed, which is duplicate copy of first. Regardless of clicks only one copy shld be displayed on the grid.

the code is:


C#
public partial class Form1 : Form
    {
        SqlConnection con = null;
        string connection = "";
        DataSet ds =new DataSet("Comapny");
        SqlDataAdapter da = null;
        SqlCommandBuilder cb = null;
        public string str ;
        public Form1()
        {
            InitializeComponent();
            connection = ConfigurationManager.ConnectionStrings["Mycon"].ConnectionString;
            
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            
        }

        private void InitializeConnection()
        {
            
            con = new SqlConnection(connection);
            con.Open();
            if (textBox1.Text == "1")
            {
                str = "CompDetails";
                da = new SqlDataAdapter("select * from CompDetails", con);
                
            }
            if (textBox1.Text == "2")
            {                
                str = "Orders";
                da = new SqlDataAdapter("select * from Orders", con);
            }

            cb = new SqlCommandBuilder(da);
            da.InsertCommand = cb.GetInsertCommand();
            da.DeleteCommand = cb.GetDeleteCommand();
            da.UpdateCommand = cb.GetUpdateCommand();
            da.Fill(ds, str);
            
            dataGridView1.DataSource = ds;
            dataGridView1.DataMember = str;
            
        }

        private void button1_Click(object sender, EventArgs e)
        {
            InitializeConnection();
            da.Update(ds, str);
                    
        }
    }
}
Posted
Updated 15-Oct-11 1:38am
v6

1 solution

At the beginning of the InitializeConnection(), or at least before Fill() is called, you need to clear the existing data from the dataset:
C#
ds.Clear(); // removes all rows from all tables
 
Share this answer
 
Comments
manu g m 15-Oct-11 6:36am    
Thanks Joat it worked. THanks for the solution :)
Other solution which i found is to localize the dataset instance. i.e within initializeconnection create ds=new DataSet().

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900