1

I have a datagridview binding with data coming from database that works fine. It is loaded with data when the form loads. As per client requirement I have added new button column to datagrid view by using the following code

private void form1_load
{
           var productsbycount = abc.products.GroupBy(x => x.product_Id).Select(a => new
        {
            productid = a.Key,
            prouctnam = a.FirstOrDefault().product_Name,
            productimage = a.FirstOrDefault().product_Image,
            productdescr = a.FirstOrDefault().product_Description,
            stockavailable = a.LongCount(),
            productprice = a.FirstOrDefault().product_Price
        });

        productbindingsource.DataSource = productsbycount;
        productgridview.DataSource = productbindingsource;
        DataGridViewButtonColumn buttoncolumn = new DataGridViewButtonColumn();
        productgridview.Columns.Add(buttoncolumn);
        buttoncolumn.Text = "Buy";
        buttoncolumn.HeaderText = "Buy";
        buttoncolumn.UseColumnTextForButtonValue = true;
        buttoncolumn.Name = "btnbuy";
        productgridview.Columns[0].Visible = false;

}

when the form load its working fine.

but I am checking the conditions like if we select the any of the item in something like in list view the datagrid view is sorted according to the selected item ... for that I have done like this....

if (lstviewcategories.SelectedItems[0].Value.ToString() == "All")
{
    var productsbycount = abc.products.GroupBy(x => x.product_Id).Select(a => new
      {
          productid = a.Key,
          prouctnam = a.FirstOrDefault().product_Name,
          productimage = a.FirstOrDefault().product_Image,
          productdescr = a.FirstOrDefault().product_Description,
          stockavailable = a.LongCount(),
          productprice = a.FirstOrDefault().product_Price
       });

       productbindingsource.DataSource = productsbycount;
       productgridview.DataSource = productbindingsource;
       DataGridViewButtonColumn buttoncolumn = new DataGridViewButtonColumn();
       productgridview.Columns.Add(buttoncolumn);
       buttoncolumn.Text = "Buy";
       buttoncolumn.HeaderText = "Buy";
       buttoncolumn.UseColumnTextForButtonValue = true;
       buttoncolumn.Name = "btnbuy";
       productgridview.Columns[0].Visible = false;
}
  • if i click on listview first item( "All") the datagrid view is working fine ....
  • if i click again on listview first item("All") the button column is appearing two times ....
  • if i click again on listview first item("All") the button column is appearing three times...

This is what happening for all items in listview.

My question is, is there any other way to add button column to datagrid view?

I have tried to add the button column in form1.cs[design] this will effect the actual columns in the datagridview. I am working in winforms with c# language. Can any one suggest any idea about these?

Suppose if I remove the below code in this loop

if (lstviewcategories.SelectedItems[0].Value.ToString() == "All")
{
}

The actual button column disappeared. Would any one please help on this.

MODIFIED CODE :

FIRST CONDITION : if (lstviewcategories.SelectedItems[0].Text.ToString() == CategoryType.Type2) {

                 var productsbycount = abc.products.GroupBy(x => x.product_Id).Where(a => a.FirstOrDefault().product_Price > 0 && a.FirstOrDefault().product_Price <= 1000)
                              .Select(a => new
                              {
                                  productid = a.Key,
                                  prouctnam = a.FirstOrDefault().product_Name,
                                  productimage = a.FirstOrDefault().product_Image,
                                  productdescr = a.FirstOrDefault().product_Description,
                                  stockavailable = a.LongCount(),
                                  productprice = a.FirstOrDefault().product_Price
                             });
                 productbindingsource.ResetBindings(false);
                 /*productbindingsource.DataSource = productsbycount;
                 productgridview.DataSource = productbindingsource;
                 DataGridViewButtonColumn buttoncolumn = new DataGridViewButtonColumn();
                 productgridview.Columns.Add(buttoncolumn);
                 buttoncolumn.Text = "Buy";
                 buttoncolumn.HeaderText = "Buy";
                 buttoncolumn.UseColumnTextForButtonValue = true;
                 buttoncolumn.Name = "btnbuy";
                 productgridview.Columns[0].Visible = false;*/


             }

Second condition :

           if (lstviewcategories.SelectedItems[0].Text.ToString() == CategoryType.Type3)
             {
                 var productsbycount = abc.products.GroupBy(x => x.product_Id).Where(a => a.FirstOrDefault().product_Price > 500 && a.FirstOrDefault().product_Price <= 1000)
                              .Select(a => new
                              {
                                  productid = a.Key,
                                  prouctnam = a.FirstOrDefault().product_Name,
                                  productimage = a.FirstOrDefault().product_Image,
                                  productdescr = a.FirstOrDefault().product_Description,
                                  stockavailable = a.LongCount(),
                                  productprice = a.FirstOrDefault().product_Price
                              });
                 productbindingsource.ResetBindings(false);
              /* productbindingsource.DataSource = productsbycount;
                 productgridview.DataSource = productbindingsource;
                 DataGridViewButtonColumn buttoncolumn = new DataGridViewButtonColumn();
                 productgridview.Columns.Add(buttoncolumn);
                 buttoncolumn.Text = "Buy";
                 buttoncolumn.HeaderText = "Buy";
                 buttoncolumn.UseColumnTextForButtonValue = true;
                 buttoncolumn.Name = "btnbuy";
                 productgridview.Columns[0].Visible = false;*/

             }

these tow conditions are not working ..

Glory Raj
  • 17,397
  • 27
  • 100
  • 203
  • have you just copied the code again? it seems so - you add another buttoncolumn in your code above... – Random Dev Aug 25 '11 at 13:16
  • i have a porblem with button column ...... – Glory Raj Aug 25 '11 at 13:18
  • @ckoenig would you pls solve my problem.... – Glory Raj Aug 25 '11 at 14:30
  • We are here to help and give advice not write the entire code piece for you =) – Paul C Aug 25 '11 at 14:35
  • CodeBlend has a point here - I think *we* work on the problem for some "questions" now ... as far as I can tell the answer given below is what you need. I really try to help but maybe you should try and get a bit more into the subject. As I understand you will sell this code to some client and I don't think that this Spaghetticode/blend of yours and StackOverflows will help you in the long run – Random Dev Aug 25 '11 at 14:52

2 Answers2

2

Firstly I would strongly recomend reading up on the DRY principle. To answer your question I would recomend using the refresh method of your BindingSource so that you can refresh the data in your datagridview without changing the datastructure. You should only do all of the following once on load, then refresh the data anywhere else unless you actually want to change the datatype e.g. the data is coming from a different source;

productbindingsource.DataSource = productsbycount;
        productgridview.DataSource = productbindingsource;
        DataGridViewButtonColumn buttoncolumn = new DataGridViewButtonColumn();
        productgridview.Columns.Add(buttoncolumn);
        buttoncolumn.Text = "Buy";
        buttoncolumn.HeaderText = "Buy";
        buttoncolumn.UseColumnTextForButtonValue = true;
        buttoncolumn.Name = "btnbuy";
        productgridview.Columns[0].Visible = false;

Instead of doing this all again in the following code block just call productbindingsource.ResetBindings(false);

if (lstviewcategories.SelectedItems[0].Value.ToString() == "All")
            {
            }

UPDATE: Also instead of defining the var productsbycount in this code block, make it a class variable at the very top so that you can access it all your methods, that way when you refresh the data you will have overwritten the previous var productsbycount and it will work marvellously.

UPDATE2: 'ResetBindings() can be used at any point after you have changed the data but as I have already said, you need a class level variable (AKA putting var productsbycount at the top of the class) and in this example it would go after this;

productprice = a.FirstOrDefault().product_Price
           });

UPDATE3: I repeat we are here to help and give advice not write the entire code piece for you but as I am feeling nice =) I also repeat there appears to be a great deal of duplication here and as the code base grows this may cause you great pain!;

namespace Test
{
    public partial class Form2 : Form
    {
        BindingSource productbindingsource;
        var productsbycount;

        public Form2()
        {
            InitializeComponent();
            Load += new EventHandler(Form2_Load);
        }

        void Form2_Load(object sender, EventArgs e)
        {
            productsbycount = abc.products.GroupBy(x => x.product_Id).Select(a => new
            {
                productid = a.Key,
                prouctnam = a.FirstOrDefault().product_Name,
                productimage = a.FirstOrDefault().product_Image,
                productdescr = a.FirstOrDefault().product_Description,
                stockavailable = a.LongCount(),
                productprice = a.FirstOrDefault().product_Price
            });
            productbindingsource.DataSource = productsbycount;
            productgridview.DataSource = productbindingsource;
            DataGridViewButtonColumn buttoncolumn = new DataGridViewButtonColumn();
            productgridview.Columns.Add(buttoncolumn);
            buttoncolumn.Text = "Buy";
            buttoncolumn.HeaderText = "Buy";
            buttoncolumn.UseColumnTextForButtonValue = true;
            buttoncolumn.Name = "btnbuy";
            productgridview.Columns[0].Visible = false;
        }

        private void methodNameHere()
        {
            productsbycount = abc.products.GroupBy(x => x.product_Id).Where(a => a.FirstOrDefault().product_Price > 0 && a.FirstOrDefault().product_Price <= 1000)
                              .Select(a => new
                              {
                                  productid = a.Key,
                                  prouctnam = a.FirstOrDefault().product_Name,
                                  productimage = a.FirstOrDefault().product_Image,
                                  productdescr = a.FirstOrDefault().product_Description,
                                  stockavailable = a.LongCount(),
                                  productprice = a.FirstOrDefault().product_Price
                              });

            productbindingsource.ResetBindings(false);
        }
    }
}
Paul C
  • 4,687
  • 5
  • 39
  • 55
  • Please re-phrase/expand the question, I am not sure what you mean – Paul C Aug 25 '11 at 13:23
  • The `ResetBindings()` method - [Causes a control bound to the BindingSource to reread all the items in the list and refresh their displayed values.](http://msdn.microsoft.com/en-us/library/system.windows.forms.bindingsource.resetbindings.aspx) – Paul C Aug 25 '11 at 13:30
  • Did this help you with your problem, can you follow it? – Paul C Aug 25 '11 at 13:56
  • You have put the `ResetBindings()` in the right place but in order for it to work correctly you need to move your variable creation to the top of your class (so all methods can access it) then just set it in your if statement WITHOUT `var`, as follows: productsbycount = tgs.products.GroupBy(x => x.product_Id).Where(a => a.FirstOrDefault().product_Price > 500 && a.FirstOrDefault().product_Price <= 1000) – Paul C Aug 25 '11 at 14:34
  • @user899271 let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/2883/discussion-between-codeblend-and-user899271) – Paul C Aug 26 '11 at 08:52
  • Taking another look at the code you have put on here it looks like an awful lot of duplication and this will trip you up as your code base grows espicially if want to change functionality and you have to go back and manually update all the places you duplicated code! – Paul C Aug 26 '11 at 09:00
  • any way this is not working at all..... and how do u declare var productbycount in the form at the top.... – Glory Raj Aug 30 '11 at 18:19
0

many thanks for your support ,I have solved my problem....like this... At the form load i have added the button column to datagrid view ......and when i am checking the conditions like this below..

if (lstviewcategories.SelectedItems[0].Text.ToString() == CategoryType.Type2)

I have just assigned like the below....

productgridview.datasource = productsbycount.Where(a => a.FirstOrDefault().product_Price > 0 && a.FirstOrDefault().product_Price <= 1000)  

Luckily it was working fine .......

Glory Raj
  • 17,397
  • 27
  • 100
  • 203