Solved

List box selected Index event

Posted on 2007-12-05
9
793 Views
Last Modified: 2008-02-01
My question is :

I have a console screen....which accepts user info ,when I enter userfirstname/lastname and click on a search button names related to that type will appear in the datagrid view ..for suppose I have a firstname called dave then  users with first name dave will come in the datagrid view .....it might be any number of rows....If I select the first row all that users information is displayed ....I mean his billing address,personal details and the products he registere....so now the products he registered would come up through datasource and are populated in the list box.....

Now the problem:

First time when I select a user /row it populates his products in list  box and the control is not highlighted as the code runs through listbox1.selectedindex=-1
second time when I click the row in datagridview control automatically hits the first name in the lsit box and reads the information without even selecting the name............the information inside that is popped up through a msg box.........now when I click on ok in the msg box...........then its going through listbox.selectedindex=-1 and does not highlight any thing...........

I want a work around to solve this .
0
Comment
Question by:onebite2
  • 5
  • 3
9 Comments
 
LVL 21

Expert Comment

by:surajguptha
ID: 20415803
How would you want it to behave?
What events have you written for the listitem?
0
 
LVL 10

Expert Comment

by:Nash2334
ID: 20415827
Wow, OK let me see if I have this straight.  You have:

1. Textboxes in which a user enters a first and/or last name and clicks a search button.  All items matching that search are populated in a DataGridView.

2. When a row is selected in the DataGridView, you populate a ListBox control with a list of products.

I believe you are trying to do something when an item in the ListBox is selected, but it is not clear from your post.  Can you elaborate on:

1. What do you want to happen when an item in the ListBox is selected?
2. What events are you wiring to in the DataGridView and ListBox?
0
 

Author Comment

by:onebite2
ID: 20417028
The points 1 and 2 are correcta nd coming to list box selection:

When an item in the list box is selected it pops up a message box with details of the item like its license information.

EVENTS IN list Box:
List box selected Index event:
Datagridview_click.


Now my problem is first time when I select a row its showing all the products and the first product is not highlighted until and unless I select,but next time when I clcik a row control automatically goes to the top most item in the list and its license info is being displayed without even being slected............I feel first time the items are not being cleared but not sure what would be the problem....
Here goes my sample code for listbox and datagridview:

Any help would be appreciated!


//Populating List Box with productNames
        private List<UserData.ProductsRegistered> proreg;
 
        private void ProductsRegistered(string UserName, string productID,string Name)
        {
            proreg =userdata.GetRegisteredProducts(UserName, productID,Name);
 
            listBox1.DataSource = proreg;
            listBox1.DisplayMember = Name;
           listBox1.SelectedIndexChanged += new EventHandler(this.listBox1_SelectedIndexChanged);
           listBox1.SelectedIndex = -1;
           listBox1.Refresh();
            
                                      
        }
 
        //selecting individual items in a list box
 
 
        private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            // Get the currently selected item in the ListBox.
 
            string Name = "";
            string UserId = "";
            string SerialNumber = "";
            string UserName = "";
            string ProductId = "";
 
 
            //populate the product Name and load the listbox with all values
            if (null != listBox1.SelectedItem)
            {
 
                Name = listBox1.SelectedItem.ToString();
 
                UserData.Name info = userdata.GetInfoName(UserName, Name);
                ProductId = info.ProductId;
 
                UserData.UID ui = userdata.GetUserID(ProductId);
                UserId = ui.UserId;
 
                UserData.LicenseInfo LInfo = userdata.GetNameInfo(UserId, ProductId, Name);
                SerialNumber = LInfo.SerialNumber;
 
                int _count = listBox1.Items.Count;
                if (_count != 0)
                {
                    for (int i = 0; i < _count; i++)
                    {
                        if ((listBox1.GetSelected(i)))
                        {
                            MessageBox.Show("Serial No:= " + SerialNumber.ToString() + "UserID:= " + UserId.ToString(), "LicenseInfo");
                            
                        }
                        
                     }
                }
            }
            //If listbox values to be cleared.
            else
            {
                
                if (listBox1.SelectedIndex > -1)
                    listBox1.Items.Clear();
 
            }
        }
 
Datagrid view clcik:
 
private void dataGridView1_Click(object sender, EventArgs e)
        {
            foreach (Control c in groupBox2.Controls)
            {
                c.Visible = true;
            }
            ltemp1.Visible = false;
            ltemp.Visible = false;
            string UserID = "";
            string ProductID = "";
            string Name = "";
           
            textBox1.Text = dataGridView1.CurrentRow.Cells[1].Value.ToString();
            textBox2.Text = dataGridView1.CurrentRow.Cells[2].Value.ToString();
            textBox3.Text = dataGridView1.CurrentRow.Cells[5].Value.ToString();
            textBox4.Text = dataGridView1.CurrentRow.Cells[3].Value.ToString();
            listBox1.SelectedIndex = -1;
         //   listBox1.ClearSelected();
     
            string BillingId = dataGridView1.CurrentRow.Cells[6].Value.ToString();
            string CreditCardID = dataGridView1.CurrentRow.Cells[7].Value.ToString();
            DataTable dtd = userdata.GetUserRegisteredProducts(textBox12.Text);
            UserID = dtd.Rows[0][3].ToString();
            ProductID = dtd.Rows[0][0].ToString();
            dtd = userdata.GetProductName(ProductID);
 
        
           
            if (BillingId != "-1")
            {
                BillingAddress(textBox4.Text, BillingId);
 
            }
 
            else
            {
 
            foreach (Control c in groupBox2.Controls)
                {
                    c.Visible = false;
                }
                ltemp1.Visible = false;
                ltemp.Visible = false;
                ltemp1.Text = "No Billing Address Stored";
                ltemp1.Location = new Point(50, 50);
 
                groupBox2.Controls.Add(ltemp1);
                ltemp1.Visible = true;
 
 
            }
     
            if (ProductID != "")
            {
                ProductsRegistered(textBox4.Text, ProductID,Name);
                listBox1.DataSource = proreg;
                listBox1.DisplayMember = Name;
              
              
               
            }
            else
            {
          
                foreach (Control c in groupBox4.Controls)
                {
                    c.Visible = true;
                }
 
            }
            
                       
            if (CreditCardID != "-1")
            {
                CreditCard(textBox4.Text, CreditCardID);
            }
 
            else
            {
 
                foreach (Control c in groupBox3.Controls)
                {
                    c.Visible = false;
                }
 
                ltemp.Text = "No Credit Card Stored";
                ltemp.Location = new Point(50, 50);
 
                groupBox3.Controls.Add(ltemp);
                ltemp.Visible = true;
            }
           
        }

Open in new window

0
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

 
LVL 10

Expert Comment

by:Nash2334
ID: 20420353
OK, so after the row is selected in the DataGridView you want the first item in the ListBox to be selected automatically?  A couple of notes:

1. You should probably wire to the DataGridView's SelectionChanged event rather than Click - Click is going to fire all over the place.

2. If you want the first item in the ListBox to be selected automatically when the row in the DataGridView is selected, you need to do so programmatically:
            if (ProductID != "")
            {
                ProductsRegistered(textBox4.Text, ProductID,Name);
                listBox1.DataSource = proreg;
                listBox1.DisplayMember = Name;        
                
                if (listBox1.Items.Count > 0)
                    listBox1.SelectedIndex = 0;
            }

Open in new window

0
 
LVL 10

Expert Comment

by:Nash2334
ID: 20420398
As a sidebar, you should really avoid using operators on strings; if you want to compare a value to a string, you should use Equals.  You can also case integers to their numeric representations if you want to use numeric operators.
if (ProductID.Equals(string.Empty))
{
    ...
}
 
int CreditCardID = (int)dataGridView1.CurrentRow.Cells[7].Value;

Open in new window

0
 

Author Comment

by:onebite2
ID: 20421036
Hey Nash,

Thanks for the advice I will definately follow....

I mean after the row is selected I want the values to be populated in list box ....that is done through datasource.........but I don't want the control to automatically go to the first item.......list box should be populated without highlighting any items.................only if the user clicks then only it should display thedetails in that particular item.......


So datagridview click event should be changed to datagrid view selection changed event???????will that solve?

0
 
LVL 10

Expert Comment

by:Nash2334
ID: 20422027
Just unwire the ListBox SelectedIndexChanged event before you assign the datasource and rewire it when you are done.
listBox1.SelectedIndexChanged -= new EventHandler(listBox1_SelectedIndexChanged);
 
if (ProductID != "")
{
	ProductsRegistered(textBox4.Text, ProductID,Name);
	listBox1.DataSource = proreg;
	listBox1.DisplayMember = Name;        
}
 
listBox1.SelectedIndexChanged += new EventHandler(listBox1_SelectedIndexChanged);

Open in new window

0
 

Author Comment

by:onebite2
ID: 20422323
Yeah I did the same thing and it seems to be working......Can you explain me in detail what would be the reason?

I have been thinking around this problem since 4 days......finally it got resolved.........

Thanks a lot Nash!I really have no words to appreciate your help!
Once again Thank you!
0
 
LVL 10

Accepted Solution

by:
Nash2334 earned 500 total points
ID: 20422479
No problem.  Essentially when you databind an object as the datasource of a ListBox, DataGridView, etc., you can run into situations where you cause events to fire inadvertently, as was the case here.  By unwiring the SelectedIndexChanged event before you databind the ListBox you prevent the event from firing unexpectedly.  You then rewire event so that when a user makes a selection, it behaves accordingly.
0

Featured Post

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
HTTPS jquery doesn't work 9 63
Problem!!! 8 33
Problem with SelectList in .NET MVC application 1 17
Dot Net 4.6.1 installation fails on W2012 R2 server 14 20
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

803 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question