Solved

Listbox selecteditem event

Posted on 2007-11-30
45
1,574 Views
Last Modified: 2013-12-16
I have  a listbox whose list is  being populated through a datasource ...That list contains names of some products.when the list is being populated control goes to the first name on the list ....and without even selecting the first name its popping up the details of that name. I used listbox.selectedindex=-1;it worked for a while...

But my scenario is I have a datagrid which contains so many rows if I select on one row then listbox populates with those values through datasource and here the lsitbox1.selectedindex=-1 is working but now if I select an other row after that ..the values are populated in the list box but the control goes to the first name and displays its details.....how do I fix this??

I feel the values in the listbox are not being cleared or refreshed....so that next time when I am selecting another row its showing some of the values which are already there in the first one.....not sure but my vague guess....
Help is appreciated!

Thanks!

Here goes my sample code
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);

           //In a list box the control automatically goes to the first place but should be fired only 

            //if the first element is selected....to avoid the control being highlighted use selected index

            listBox1.SelectedIndex = -1;

                                         

        }

 

        //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 = "";

            // Name= listBox1.SelectedItem.ToString();

            // string Name = listBox1.SelectedItem.ToString();

            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;

 

                //where i =[0] to [6] for example username=chambo1

                //i[0]=ioloantivirus1

                //i[1]=systemmechanic 7 professional

                //i[2]=....

                //Loop through and check the count ....items are added through datasource property..

                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

            {

                ////listBox1.Items.Clear();

                // listBox1.SelectedIndex = -1;

                 if (listBox1.SelectedIndex > -1)

                     listBox1.Items.Clear();

 

            }

        }

Open in new window

0
Comment
Question by:onebite2
  • 22
  • 22
45 Comments
 
LVL 11

Expert Comment

by:Mihai Stancescu
Comment Utility
If you use in the list box the data binding you must use ListBox1.SelectedValueChanged instead of ListBox1.SelectedItndexChanged event.

Also you must add the ValueMember property of the list box for this event to work.

This should fix the problem.

Hope this helps!

Regards,
Mishu
0
 
LVL 22

Expert Comment

by:p_davis
Comment Utility
as i had mentioned in the other thread that you had started there is a row focus changed event. it is called RowEnter. attach this event to your code and you can do the selectedindex=-1 again in this event. it will work like it does the first time you load your form

also, if you are starting a new thread you might want to close the other questions that are involved (assign points, request deletion whatever your feel is appropriate).


dataGridView1.RowEnter +=  new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_RowEnter);
 

        private void dataGridView1_RowEnter(object sender, DataGridViewCellEventArgs e)

        {

           listBox1.SelectedIndex = -1;

        }

Open in new window

0
 

Author Comment

by:onebite2
Comment Utility
Hey Davis,

When I inserted this event in my data gridview1_cellcontentclick_1 ....it is not highliting the first item when I clcik the datagrid for the first time its showing all the products of that user........but now after using the row enter event...when I click the second row in the  datagrid view on the it is not highlighting but it is showing the products of the first user instead of this user (current user)....Please give me any idea to work around this???

Thanks!
  private void dataGridView1_CellContentClick_1(object sender, DataGridViewCellEventArgs e)

        {
 

   dataGridView1.RowEnter +=  new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_RowEnter);
 

          

        }
 

private void dataGridView1_RowEnter(object sender, DataGridViewCellEventArgs e)

        {

            listBox1.SelectedIndex = -1;

        }

Open in new window

0
 

Author Comment

by:onebite2
Comment Utility
Hey Davis,

I mean when I clcik the datagrid it is directly firing the row enter event instead of iterating through teh list box and getting new values for the next user....and clearing the old values .....

Thanks !
0
 
LVL 22

Expert Comment

by:p_davis
Comment Utility
thanks for the clarification

i think that you might want to call your function that does this for you in the event and if the original setting of selectedindex = -1 is in there then you wouldn't have to set it again.
0
 

Author Comment

by:onebite2
Comment Utility
So what do you think I have to do??????How can I call that function?Here goes the code attached for listbox and datagridview....
 //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();

          // dataGridView1.RowEnter += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_RowEnter);

            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;

            }

           

        }

private void dataGridView1_CellContentClick_1(object sender, DataGridViewCellEventArgs e)

        {

 

   dataGridView1.RowEnter +=  new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_RowEnter);

 

          

        }

 

private void dataGridView1_RowEnter(object sender, DataGridViewCellEventArgs e)

        {

            listBox1.SelectedIndex = -1;

        }

Open in new window

0
 
LVL 22

Expert Comment

by:p_davis
Comment Utility
did you ever have anything in the  cell content clicked event method?
you would probably want to hook into that row enter event on the form load instead of in the cellcontentclick
0
 

Author Comment

by:onebite2
Comment Utility
No there is nothing in the cellcontent clicked event method...............but my form load just loads a blank screen ....I feel there is no point in calling the row enter event at that place...........as I want the row event to be fired after I select one row and some values are displayed then I want the row values to be displayed without higlighting the first item.......


Let me know if u have any work around???Thanks!
0
 
LVL 22

Expert Comment

by:p_davis
Comment Utility
the += adds that event to your form it doesn't really matter where you put it. you only need to have it called once though (it doesn't actually call that event it just lets you handle that event).


if i understand what you are needing you basically are saying that you want the code that is in the selectedindex event method called.-- if this is so then you can put that code in another method and call it in both places.


hopefully i am understanding
private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)

        {

ProcessInfo(false);

}
 

private void dataGridView1_RowEnter(object sender, DataGridViewCellEventArgs e)

        {

            ProcessInfo(true);

        }
 

private void ProcessInfo(bool rowFocusChange)

{

          //added this b/c you don't want to set the index

          //back to -1 if selecting an item from the listbox

          if(rowFocusChange)

           listBox1.SelectedIndex = -1;
 

            // 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();

 

            }

}

Open in new window

0
 

Author Comment

by:onebite2
Comment Utility
Hey Davis,

I did try this but it isn't working see I will explain the scenario again...........how its throwing me an error........

I have a datagridview with 3 rows when I click for the first time on one row its populating the list box with values from database and it is not highlighting the first item ...only if I select an item then only its popping the details....for suppose I have caramel and choco as my items populated through dtaasource in the lsit box.....when I click on caramel it should show its details........

Now when I click on 2nd row of the datagird and it populates item caramel ...here it is directly populating the value into the lsit box and selecting the first item and popping its value..........

I tried the way you suggested me earlier but No clue it isn't working........
Suggest me if you have any idea for this problem..........
Thanks!
0
 
LVL 22

Expert Comment

by:p_davis
Comment Utility
you called the ProcessInfo method in both the selectedindex changed event and the row enter event?

what if you call your ProductsRegistered method in the rowenter event instead of calling the processinfo()

since you want the items do load on row focus changed.

what i am getting from you is that you want the list to be fresh every time you click on a new row.
on first row click there is no selected item-- then you choose one.
if you go to another row you (want the same list?) want the list to look fresh again with no details populated for the item that was last selected.

what are you using to display the details of the selected item? and what variables are they using?
0
 

Author Comment

by:onebite2
Comment Utility
I called the process Info method in both SelectedIndex Changed Event an din the Row enter event....but this did not work..........First when I click the grid listbox is populated with values and second time I clcik the grid control goes to the top one......and row enter event did not fire when clciking the row for 2nd time............then there is no point in claling the products registered method..........

Yes everytime I clcik on a new row list should be fresh and load with new values....
first row there is no item selected only the user shouled click on the item to be fired......
If I click on the nesxt row new values should be populated and old ones to be cleared..........and look fresh again...

Let me tell you  in this grid each row is one user say 1st row details are about an user sam,then next row user details are about an other user dave....so if we click on one row then products registered by that user will be populated in lsit box....
now when I click on next row products reg by that particular user should be populated....

All this code is working fine...........except that before selecting the top most item the control defaultly goes there and displays information contained in that item..........

Variables used to display selected item are userid,productid.....but Product Name should be displayed......

Well I am pasting the whole code related to this listbox..............both in form1.cs and userdata.cs ....
Some methods are called in Userdata with inline sql.......

Just let me know if u find any worka round..
Thanks!
Form1.cs:

 //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);

           //In a list box the control automatically goes to the first place but should be fired only 

            //if the first element is selected....to avoid the control being highlighted use selected index

           listBox1.SelectedIndex = -1;

           //listBox1.Refresh();

            

                                      

        }
 

        //selecting individual items in a list box
 

        //private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)

        //{

        //    ProcessInfo(false);

        //}
 

        private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)

        {

        //private void ProcessInfo(bool rowFocusChange)

        //{

        //    if (rowFocusChange)

        //        listBox1.SelectedIndex = -1;

 
 

            // Get the currently selected item in the ListBox.
 

            string Name = "";

            // Name= listBox1.SelectedItem.ToString();

            // string Name = listBox1.SelectedItem.ToString();

            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;
 

                //where i =[0] to [6] for example username=chambo1

                //i[0]=ioloantivirus1

                //i[1]=systemmechanic 7 professional

                //i[2]=....

                //Loop through and check the count ....items are added through datasource property..

                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");

                            

                        }

                        //listBox1.Refresh();

                     }

                }

            }

            //If listbox values to be cleared.

            else

            {

                ////listBox1.Items.Clear();

                //listBox1.SelectedIndex = -1;

                if (listBox1.SelectedIndex > -1)

                    listBox1.Items.Clear();
 

            }

        }

 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;

            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;

            }

           

        }
 

UserData.cs:
 

 //Populates the values in the Listbox.

    public class ProductsRegistered

    {

        public string ProductID ;

        public string Name;

      

        

        public override string ToString()

        {

             return Name;

            //both ID and Name to be displayed.

            //return Name + " - " + ProductID;
 

        }

    }

 

    public List<ProductsRegistered> GetRegisteredProducts(string UserName, string ProductID,string Name)

    {

 

        List<ProductsRegistered> productList = new List<ProductsRegistered>();

 

        string commandText = 

            string.Format("SELECT DISTINCT a.UserID,a.ProductID,b.[Name] as Name" +

            "  FROM myacc_userregisteredProducts a " + 

            "    INNER JOIN InstallationProduct b ON a.ProductID=b.[ID]" +

            "    INNER JOIN myacc_users c ON a.UserID=c.[ID]" +

            "  WHERE c.UserName ='{0}' ", UserName);

                

     using (SqlConnection connection = new SqlConnection("server=Int; database=sv; uid=sa; pwd=ore"))

        {

            connection.Open();

            using (SqlCommand command = new SqlCommand(commandText, connection))

            {

                using (SqlDataReader reader = command.ExecuteReader())

                {

                    while (reader.Read())

                    {

                       ProductsRegistered product = new ProductsRegistered();

                        

                        // product.ProductID = int.Parse(reader["ProductID"].ToString());

                        product.ProductID = reader["ProductID"].ToString();

                        product.Name = reader["Name"].ToString();
 

                        productList.Add(product);

                                                                      

                   }

                    return productList;

                }

            }

        }

 

    }

        // To Display License Information to the values in the ListBox.

        public struct Name

        {

           // public string UserId;

            public string ProductId;

        }
 

        public Name GetInfoName(string UserName,string Name)

        {
 

            Name info = new Name();

       

            DataTable dtUsers = new DataTable();

            string strSQL = "SELECT ID as ProductId from InstallationProduct where Name='" + Name+ "'";

            SqlConnection sqlConn = new SqlConnection("server=Intr; database=sv; uid=sa; pwd=!ore");

            sqlConn.Open();

            SqlCommand cmd = new SqlCommand(strSQL, sqlConn);

            SqlDataReader dr = cmd.ExecuteReader();
 

            if (dr.Read())

            {

                info.ProductId = dr[0].ToString();

                // info.UserId = dr[1].ToString();
 

            }

            else

            {

                info.ProductId = null;

            }
 

            dr.Close();

            sqlConn.Close();

            return info;

        }

        public struct UID

        {

            public string UserId;

           // public string productId;
 

        }
 

        public UID GetUserID(string ProductId)

       

          {
 

              UID ui = new UID();

            

            DataTable dtUsers = new DataTable();

            string strSQL = "SELECT UserId from svc_ioloserialNumbers where productId='" + ProductId + "'";

           // string strSQL = "SELECT UserId from svc_ioloserialNumbers where Cast(productId AS VARCHAR) ='" + ProductId + " '";

            SqlConnection sqlConn = new SqlConnection("server=Intr; database=sv; uid=sa; pwd=ore");

            sqlConn.Open();

            SqlCommand cmd = new SqlCommand(strSQL, sqlConn);

            SqlDataReader dr = cmd.ExecuteReader();
 

            if (dr.Read())

            {
 

                ui.UserId = dr[0].ToString();
 

            }

            //If UserId=null

            else

            {

                ui.UserId = "No UserId";

            }

            dr.Close();

            sqlConn.Close();

            return ui;

        }
 

     

        public struct LicenseInfo

        {

          // public string UserId;

           public string SerialNumber;

        }
 

        //To display serial number and id in the listbox

        public LicenseInfo GetNameInfo(string UserId,string ProductId,string Name)

        {
 

            DataTable dtUsers = new DataTable();

            LicenseInfo LInfo = new LicenseInfo();
 
 

           // String strSQL = (" SELECT a.UserId, a.SerialNumber" +

           // " FROM  svc_ioloSerialNumbers a " +

           // "    INNER JOIN svc_Subscriptions b ON a.SerialNumber = b.SerialNumber " +

           //"   Where a.UserID='" + UserID + "'");
 

            //String strSQL = (" SELECT  DISTINCT a.UserId, a.SerialNumber,a.ProductID,c.[ID],c.[Name]" +

            // "FROM    dbo.svc_ioloSerialNumbers a" +

            // "  INNER JOIN dbo.svc_Subscriptions b ON a.SerialNumber = b.SerialNumber" +

            // "  INNER JOIN dbo.InstallationProduct c ON a.ProductID=C.[ID]" +

            // " Where a.UserID='" + UserID + "'");
 

            String strSQL=" SELECT SerialNumber from svc_ioloserialNumbers where UserId='" + UserId + "'and productId='" + ProductId + "'";

           // " SELECT SerialNumber from svc_ioloserialNumbers where UserId='" + UserId + "' and productId = '" + ProductId + "'";
 

            SqlConnection sqlConn = new SqlConnection("server=Intr; database=svc; uid=sa; pwd=ore");

            sqlConn.Open();

            SqlCommand cmd = new SqlCommand(strSQL, sqlConn);

            SqlDataReader dr = cmd.ExecuteReader();
 

            if (dr.Read())

            {

                // LInfo.UserId = dr[0].ToString();

                LInfo.SerialNumber = dr[0].ToString();
 

            }

                //If no USERID THEN CLAUSE --CHECK THIS LATER

            else

            {

                LInfo.SerialNumber = "No SerialNumber";

            }
 

            dr.Close();

            sqlConn.Close();

            return LInfo;

        }
 
 
 

        //Product Name

       public DataTable GetProductName(string ProductID)

        {
 

            ArrayList arlist = new ArrayList();
 

            DataTable dtUsers = new DataTable();

            string strSQL = "SELECT Name from installationproduct where id='" + ProductID + "'";

            SqlConnection sqlConn = new SqlConnection("server=Intr; database=sv; uid=sa; pwd=ore");

            sqlConn.Open();

            SqlCommand cmd = new SqlCommand(strSQL, sqlConn);

            using (cmd)

            {
 

                SqlDataAdapter adapter = new SqlDataAdapter(cmd);

                adapter.Fill(dtUsers);
 
 
 

            }
 

            sqlConn.Close();
 
 

            return dtUsers;
 
 

        }

Open in new window

0
 
LVL 22

Expert Comment

by:p_davis
Comment Utility
well i would suggest a little breakpoint action on the selectedindex changed event. set one at the first open bracket and open the call stack window when you are debugging. make note when you click on the second concurrent row what is actually calling the selectedindex event.

i am assuming that this is being called because your selected index is getting set.
maybe with that we can determine where the problem is.

also, if you are constantly putting new info int to the List<> proreg and the info will always be different for each user you may want to call proreg.clear() when you reload it.
0
 

Author Comment

by:onebite2
Comment Utility
First time when it loads values into the listbox.....its is going through all these steps in the method and displaying the values.....it is going to  listBox1.SelectedIndex = -1; and reading the values and going to the next line  listBox1.DisplayMember = Name;....and going through listBox1.SelectedIndex = -1;....too but second time when I select after reading this line   listBox1.DataSource = proreg;....it is directly stepping into listbox selectedindex change event and firing that .........its not going through the listBox1.SelectedIndex = -1.....that should be the problem.......

Secondtime when I click the row it is firing the datagridview clcik event and then reading the values in the products Registered method....by going through this line........listBox1.datasource=proreg;ProductsRegistered
    {
        public string ProductID ;
        public string Name;
     
       
        public override string ToString()
        {
             return Name;
            //both ID and Name to be displayed.
            //return Name + " - " + ProductID;

        }
    }
and then directly getting the name from the above method and firing the selected index change event.........

I guess what you said was correct ...I should clear the proreg each time I reload it....probably.........But can you tell me where should I put this step??????????proreg.clear()?????????

 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);
           //In a list box the control automatically goes to the first place but should be fired only
            //if the first element is selected....to avoid the control being highlighted use selected index
           listBox1.SelectedIndex = -1;
           //listBox1.Refresh();
           
                                     
        }
0
 
LVL 22

Expert Comment

by:p_davis
Comment Utility
private void ProductsRegistered(string UserName, string productID,string Name)
        {
//i would put it here
proreg.clear();

            proreg =userdata.GetRegisteredProducts(UserName, productID,Name);

            listBox1.DataSource = proreg;
            listBox1.DisplayMember = Name;
           listBox1.SelectedIndexChanged += new EventHandler(this.listBox1_SelectedIndexChanged);
           //In a list box the control automatically goes to the first place but should be fired only
            //if the first element is selected....to avoid the control being highlighted use selected index
           listBox1.SelectedIndex = -1;
           //listBox1.Refresh();
           
                                     
        }
0
 

Author Comment

by:onebite2
Comment Utility
That didn't work its throwing null exception error if I put at that place............because it will load null values .....
0
 
LVL 22

Expert Comment

by:p_davis
Comment Utility
doesn't this line
            proreg =userdata.GetRegisteredProducts(UserName, productID,Name);
load data into it?

where did you get the error?
0
 

Author Comment

by:onebite2
Comment Utility
It loads the data so proreg should be after that line ..................proreg.clear();if I place this after that line ..it is clearing all the values when I click for the first time.............so first time only it is not loading values at all..........so I guess there should be some clause to embed this proreg.clear() but not sure ......how to do that?
0
 

Author Comment

by:onebite2
Comment Utility
First time when I loop through
proreg =userdata.GetRegisteredProducts(UserName, productID,Name); it goes to that particular method in the userdata.cs and reads the values but.....when it comes back to screen  it goes into this line
listbox1.datasource=proreg;At this point when I look at the values in this line..
proreg =userdata.GetRegisteredProducts(UserName, productID,Name); it reads username correct and productid and Name  values are null............
and it is going through listbox1.selectedindex=-1....that is why it is not getting highlighted..........

But second time it goes through same steps
step 1:proreg =userdata.GetRegisteredProducts(UserName, productID,Name);reads that particular method in userdata.cs
step 2.listbox1.datasource=proreg
step 3:At this point if I read the values in this line
proreg =userdata.GetRegisteredProducts(UserName, productID,Name);it is showing username with a value and product id  as null but Name with a value.....and directly hitting selected event..........as I declared
name=listbox1.selecteditem;
0
 
LVL 22

Expert Comment

by:p_davis
Comment Utility
so before hitting getregisteredproducts name should be null?

if so just set that variable to null before the method call
0
 

Author Comment

by:onebite2
Comment Utility
I don't think so we can set that to null as it says variable declared in the parent scope cannot be declared and referred to null..........
0
 
LVL 22

Expert Comment

by:p_davis
Comment Utility
you can't set it to null in the method itself, it would have to be before it is called (as needed)
0
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 
LVL 22

Expert Comment

by:p_davis
Comment Utility
what i was really asking, was the first walkthrough correct where the name and the product id are null

and thereby the second walkthrough was wrong because the name had a value.
0
 

Author Comment

by:onebite2
Comment Utility
Yes that was my guess ..........so where should I set to null?First time when it is loading it is null second time when we click it is pulling the old names and taking some value I guess..........
0
 
LVL 22

Expert Comment

by:p_davis
Comment Utility
           if (ProductID != "")
            {
               //possibly here.
                Name = null;

                ProductsRegistered(textBox4.Text, ProductID,Name);
                listBox1.DataSource = proreg;
                listBox1.DisplayMember = Name;
           }

0
 

Author Comment

by:onebite2
Comment Utility
Before the control hits this place ..........its firing the listbox selectedevent and showing the value there...................but as I told you second time when I click the grid directly the control goes to top element and pops up that info using a message box now when I clcik on ok..........of the msg box ............it shows no item is selected............something might be wrong with my code and weird ..........
0
 
LVL 22

Expert Comment

by:p_davis
Comment Utility
oh, ok -- i think that maybe you should move your selectedindex = -1 statement to the bottom of this event

dataGridView1_Click

so it is the very last thing that will be fired when you click on it
0
 

Author Comment

by:onebite2
Comment Utility
Yeah I did try this too but it isn't working..........second time when I click its holding a value ....in this line selected index is showing -1 .........that's why its going to firing selected event..........though I placed it in the datagridview its still the same........

Listbox1.selectedindex=-1
0
 
LVL 22

Expert Comment

by:p_davis
Comment Utility
what if you  add

           if (null != listBox1.SelectedItem && listBox1.SelectedIndex != -1)

to selectedindexchanged event.
0
 

Author Comment

by:onebite2
Comment Utility
Some how this is also not solving my problem.......

First when it is loaded with values it is reading blank value in listbox1.selecteditem and -1 in listbox1.selectedindex

Second time when it is reading it is reading value name in listbox1.selecteditem and 0 in listbox1.selectedindex
0
 
LVL 22

Expert Comment

by:p_davis
Comment Utility
ok so with that now we go on the hunt of what is changing the selectedindex to 0.

i think that you still might have to implement that processinfo function so you can differentiate row change and listitem index change from user selection.

if it is a row change in the gridview then go ahead and set the index to -1. go ahead and do this at the end of the method and include a return

if (rowFocusChange)
        {
           listBox1.SelectedIndex = -1;
           return;
        }
0
 

Author Comment

by:onebite2
Comment Utility
This is how I embedded rowfocus change ...now its not highlighting but first time when I clcik the datagrid view its loading some values.............the same values are being loaded even when I change the row.........instead of iterating and getting fresh values..........
 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);

           //In a list box the control automatically goes to the first place but should be fired only 

            //if the first element is selected....to avoid the control being highlighted use selected index

          listBox1.SelectedIndex = -1;

           listBox1.Refresh();

           //proreg.Clear();
 

            

                                      

        }

        private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)

        {

                  ProcessInfo(false);

         }

 

         private void dataGridView1_RowEnter(object sender, DataGridViewCellEventArgs e)

        {

            ProcessInfo(true);

        }

 

        private void ProcessInfo(bool rowFocusChange)

        {

  

     

       // private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)

       // {

        

            // Get the currently selected item in the ListBox.

            

            string Name = "";

            // Name= listBox1.SelectedItem.ToString();

            // string Name = listBox1.SelectedItem.ToString();

            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;
 

                //where i =[0] to [6] for example username=chambo1

                //i[0]=ioloantivirus1

                //i[1]=systemmechanic 7 professional

                //i[2]=....

                //Loop through and check the count ....items are added through datasource property..

                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");

                            

                        }

                        //listBox1.Refresh();

                     }

                }

            }

            //If listbox values to be cleared.

            else

            {

               

                if (listBox1.SelectedIndex > -1)

                    listBox1.Items.Clear();
 

            }

            if (rowFocusChange)

            {

                listBox1.SelectedIndex = -1;

                return;

            }

        }

Open in new window

0
 
LVL 22

Accepted Solution

by:
p_davis earned 500 total points
Comment Utility
before were you calling proreg.clear(); before or after
proreg =userdata.GetRegisteredProducts(UserName, productID,Name);?
because it should be before.
0
 
LVL 22

Expert Comment

by:p_davis
Comment Utility
did you need further assistance, why the grade of B?
0
 

Author Comment

by:onebite2
Comment Utility
I still need assistance becoz my problem is still not solved..........but you helped me a lot!
0
 
LVL 22

Expert Comment

by:p_davis
Comment Utility
well i am glad that i helped a bit, but is the same issue still occuring? or is it something different
0
 

Author Comment

by:onebite2
Comment Utility
The issue is still there not solved at all............but I feel you tried giving me some suggestions I am happy for that.........but I guess if you are okay we can start over again and it might get solved this time ............well its a small one ........but taking hard time to get solved............Let me know if you are fine so that we can start from the point where we stopped......
Thanks,
Cindy.
0
 
LVL 22

Expert Comment

by:p_davis
Comment Utility
fine by me, but i will be out for a few days with offisite design meetings and such so it may be a bit before i can respond
0
 

Author Comment

by:onebite2
Comment Utility
Yeah sure can we go ahead and start now............Is that okay.........If so do you wnat me to explain the scenario once............I wish I could solve this today............I will be really greatful to u.........
0
 
LVL 22

Expert Comment

by:p_davis
Comment Utility
ok, just so i am not assuming this listbox isn't embedded into the grid, correct?
0
 

Author Comment

by:onebite2
Comment Utility
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 slect 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 clcik 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 for this.........
Do you want me to send the code?

0
 

Author Comment

by:onebite2
Comment Utility
Yeah List box is not embedded into the grid...........its in a separate group box.........
0
 
LVL 22

Expert Comment

by:p_davis
Comment Utility
it sounds like you need to set up some kind of bindingsource so you can relate your datagrid data source (what is this by the way). and the listbox

0
 

Author Comment

by:onebite2
Comment Utility
Thanks !for your help I got my probelm solved.
0
 
LVL 22

Expert Comment

by:p_davis
Comment Utility
how did you do it, i am curious?
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Recently while returning home from work my wife (another .NET developer) was murmuring something. On further poking she said that she has been assigned a task where she has to serialize and deserialize objects and she is afraid of serialization. Wha…
This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

743 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now