Solved

How to pass name & value to listbox and then pass the selected value to a new string in C#  ?

Posted on 2009-03-29
16
422 Views
Last Modified: 2013-12-17
Hi

I have a Listbox that currently gets only name/text values passed to it.
I need to pass name & value
First I need to pass these 2 strings to the listbox instead of 1 as it is now:
TitleResultLink
TitleResultName
The TitleResultName should be visible in the Listbox to the user and TitleResultLink should be the value.
When user picks a TitleResultName in the Listbox then the TitleResultName should be passed on to Textbox2 and the value TitleResultLink to Textbox3 .



Anyone with any ideas ?
using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Collections;

using System.Windows.Forms;

using System.Net;

using System.Xml;

using System.IO;

using System.Text.RegularExpressions;
 
 
 

    public partial class Form1 : Form

    {
 

        public Form1()

        {
 

            InitializeComponent();
 

            button1.Click += new EventHandler(button1_Click);
 

        }

        

         private void button1_Click(object sender, EventArgs e)

        {

            string Search1 = "http://www.mysite.com/Search.aspx?SearchString=";

            string Search3 = "&media=0";

            string Search2 = textBox1.Text;

            string url = string.Concat(Search1, Search2, Search3);
 

            HttpWebRequest myWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);

            myWebRequest.Method = "GET";
 

            // make request for web page
 

            HttpWebResponse myWebResponse = (HttpWebResponse)myWebRequest.GetResponse();
 

            StreamReader myWebSource = new StreamReader(myWebResponse.GetResponseStream());
 

            string myPageSource = myWebSource.ReadToEnd();
 

            myWebResponse.Close();
 
 
 

            //Strip Spaces etc

            myPageSource = myPageSource.Replace("&", "&").Replace("\r", "").Replace("\n", "").Replace("\t", "").Replace("\"", "").Replace("#", "");
 
 
 

            //Parse the String and get Title and Link

            Regex Itemtitle = new Regex(@"ListItem_ItemTitle><a href=(?<Titlelink>.*?)>(?<Titlename>.*?)</a>");
 
 

            // NEW ARRAYLIST to save data

            ArrayList data = new ArrayList();
 

            //Match possible results from Html Page

            Match match;

            for (match = Itemtitle.Match(myPageSource); match.Success; match = match.NextMatch())

            {
 

                string Titlelink = match.Groups["Titlelink"].Value;

                string Titlename = match.Groups["Titlename"].Value;
 
 

                string Mysite_Url = "http://www.mysite.com";
 

                string TitleResultLink = string.Concat(Mysite_Url, Titlelink);

                string TitleResultName = (Titlename);
 
 
 

                data.Add(TitleResultName);

                 }

 

            ListBox1.Items.AddRange(data.ToArray());           

        }
 

    }

Open in new window

0
Comment
Question by:Smyken
  • 8
  • 6
  • 2
16 Comments
 
LVL 1

Expert Comment

by:counterroot
ID: 24013026
hi, in a listbox, you only able to save one element.
but you can create a struct/class/array with these values and save this in a list.

then you need the SelectedIndexChanged event:
listBox1.SelectedIndexChanged += listBox1_SelectedIndexChanged;

use the following to get the current selected item:
string item = listBox1.Items[listBox1.SelectedIndex].ToString();

so if you have the name, you can search you list (with foreach) to get the value.
example:
foreach (object o in myList)
    if (o.Value1 == item) //...

good luck!
0
 
LVL 1

Author Comment

by:Smyken
ID: 24013066
Ok

That explains why I did't find any information on passing 2 strings to listbox on google 8=)

As Im a total newb to C#, is there a chance that you could put your suggestion into my code ?

Thank you for your effort counterroot !
0
 
LVL 1

Expert Comment

by:counterroot
ID: 24013138
hi,
here is a sample code:

using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        private List<myData> data;

        private struct myData
        {
            public string Value1;
            public string Value2;
        } ;

        public Form1()
        {
            InitializeComponent();

            data = new List<myData>();

            myData d = new myData();
            d.Value2 = "a";
            d.Value1 = "aaaaaa";

            data.Add(d);

            listBox1.Items.Add("a");
            listBox1.Items.Add("b");
            listBox1.SelectedIndexChanged += listBox1_SelectedIndexChanged;
        }

        void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            string item = listBox1.Items[listBox1.SelectedIndex].ToString();
            textBox1.Text = item;

            foreach (myData d in data)
            {
                if (d.Value2 == item)
                {
                    // Do anything here
                    MessageBox.Show("found!");
                    break;
                }
            }
        }
    }
}


i hope this is helpful for you =)
0
 
LVL 1

Author Comment

by:Smyken
ID: 24013236
Sorry but I'm really lost here.
0
 
LVL 1

Expert Comment

by:counterroot
ID: 24013263
whats the problem?
0
 
LVL 1

Author Comment

by:Smyken
ID: 24013334
I just can't figure out what you mean.

My TitleResultName & TitleresultLink are 2 totally different items can't understand how I would be able to match them.
Then even if I understod your solution the I probably would have hard time implementing it to my code.
Im still trying to figure out how to understand scopes & context things.

0
 
LVL 1

Expert Comment

by:counterroot
ID: 24013384
if you select the titleresultname in your listbox, you will be able to get content the titleresultlink.
then it will be possible to compare the content of the variables lititem and the titleresultname.

perhaps you can describe your problem just a little bit more explicit.

0
 
LVL 1

Author Comment

by:Smyken
ID: 24013425
Could you please add your code to mine so that I can elaborate and maybe understand the code you wrote, like reverse engineering.
Like I said I'm totally new to C# my native language is PHP.
I have to make a small application in C# to assist a webshop that I wrote in PHP.
Some things I do understand but somethings I really need help with like this one.
I don't understand why you can't just add what you are saying to my code so that I could try it out becouse It's to complicated for me.
0
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 
LVL 1

Expert Comment

by:counterroot
ID: 24013871
hi,

try this :-)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Collections;
using System.Windows.Forms;
using System.Net;
using System.Xml;
using System.IO;
using System.Text.RegularExpressions;
 
 
 
    public partial class Form1 : Form
    {
      
            // All items
            private List<TitleResult> data;

            // Struct to save the results
        private struct TitleResult
        {
            public string TitleResultLink;
            public string TitleResultName;
        };
 
        public Form1()
        {
 
            InitializeComponent();
                  
                  // Create a new list
                  data = new List<TitleResult>();
 
                  // Register the event
                  listBox1.SelectedIndexChanged += listBox1_SelectedIndexChanged;
            button1.Click += new EventHandler(button1_Click);
 
        }
       
         private void button1_Click(object sender, EventArgs e)
        {
            string Search1 = "http://www.mysite.com/Search.aspx?SearchString=";
            string Search3 = "&media=0";
            string Search2 = textBox1.Text;
            string url = string.Concat(Search1, Search2, Search3);
 
            HttpWebRequest myWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
            myWebRequest.Method = "GET";
 
            // make request for web page
 
            HttpWebResponse myWebResponse = (HttpWebResponse)myWebRequest.GetResponse();
 
            StreamReader myWebSource = new StreamReader(myWebResponse.GetResponseStream());
 
            string myPageSource = myWebSource.ReadToEnd();
 
            myWebResponse.Close();
 
 
 
            //Strip Spaces etc
            myPageSource = myPageSource.Replace("&amp;", "&").Replace("\r", "").Replace("\n", "").Replace("\t", "").Replace("\"", "").Replace("#", "");
 
 
 
            //Parse the String and get Title and Link
            Regex Itemtitle = new Regex(@"ListItem_ItemTitle><a href=(?<Titlelink>.*?)>(?<Titlename>.*?)</a>");
 
 
            // NEW ARRAYLIST to save data
            ArrayList data = new ArrayList();
 
            //Match possible results from Html Page
            Match match;
            for (match = Itemtitle.Match(myPageSource); match.Success; match = match.NextMatch())
            {
 
                string Titlelink = match.Groups["Titlelink"].Value;
                string Titlename = match.Groups["Titlename"].Value;
 
 
                string Mysite_Url = "http://www.mysite.com";
 
                string TitleResultLink = string.Concat(Mysite_Url, Titlelink);
                string TitleResultName = (Titlename);
 
 
 
                data.Add(TitleResultName);
                 }
 
            ListBox1.Items.AddRange(data.ToArray());          
        }
            
            void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
                  // Get the name of the selected item
            string item = ListBox1.Items[ListBox1.SelectedIndex].ToString();
            textBox2.Text = item;
      
            foreach (TitleResult d in data)
            {
                if (d.TitleResultName == item)
                {
                    // Save the link in the textbox
                    textBox3.Text = d.TitleResultLink;
                    break;
                }
            }
        }
 
    }
0
 
LVL 1

Author Comment

by:Smyken
ID: 24014728
Hi

Sorry to take this long but I had to run out.
Anyhow, I just tried your suggested code without any luck.
I have been looking over it now for a good hour and I found 1 error that I corrected:

For some reason I named my listBox1 with a big L: ListBox1

But that didn't help much now I can start the application withouut debugging but with following Warning:

Warning      1      Field 'Form1.TitleResult.TitleResultLink' is never assigned to, and will always have its default value null
Warning      2      Field 'Form1.TitleResult.TitleResultName' is never assigned to, and will always have its default value null

Any ideas ?
0
 
LVL 1

Expert Comment

by:counterroot
ID: 24020541
hi,

there is another mistake (my fault :)):
I have forgotten to create a new TitleResult object. And so the list is empty.
But try this code:


using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Collections;

using System.Windows.Forms;

using System.Net;

using System.Xml;

using System.IO;

using System.Text.RegularExpressions;

 

 

 

    public partial class Form1 : Form

    {

      

        // All items

        private List<TitleResult> data;
 

        // Struct to save the results

        private struct TitleResult

        {

            public string TitleResultLink;

            public string TitleResultName;

        };

 

        public Form1()

        {

 

            InitializeComponent();

                  

            // Create a new list

            data = new List<TitleResult>();

 

            // Register the event

            listBox1.SelectedIndexChanged += listBox1_SelectedIndexChanged;

            button1.Click += new EventHandler(button1_Click);

 

        }

        

        private void button1_Click(object sender, EventArgs e)

        {

            string Search1 = "http://www.mysite.com/Search.aspx?SearchString=";

            string Search3 = "&media=0";

            string Search2 = textBox1.Text;

            string url = string.Concat(Search1, Search2, Search3);

 

            HttpWebRequest myWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);

            myWebRequest.Method = "GET";

 

            // make request for web page

 

            HttpWebResponse myWebResponse = (HttpWebResponse)myWebRequest.GetResponse();

 

            StreamReader myWebSource = new StreamReader(myWebResponse.GetResponseStream());

 

            string myPageSource = myWebSource.ReadToEnd();

 

            myWebResponse.Close();

 

 

 

            //Strip Spaces etc

            myPageSource = myPageSource.Replace("&amp;", "&").Replace("\r", "").Replace("\n", "").Replace("\t", "").Replace("\"", "").Replace("#", "");

 

 

 

            //Parse the String and get Title and Link

            Regex Itemtitle = new Regex(@"ListItem_ItemTitle><a href=(?<Titlelink>.*?)>(?<Titlename>.*?)</a>");

 

            //Match possible results from Html Page

            Match match;

            for (match = Itemtitle.Match(myPageSource); match.Success; match = match.NextMatch())

            {

 

                string Titlelink = match.Groups["Titlelink"].Value;

                string Titlename = match.Groups["Titlename"].Value;

 

 

                string Mysite_Url = "http://www.mysite.com";

 

                string TitleResultLink = string.Concat(Mysite_Url, Titlelink);

                string TitleResultName = (Titlename);

 				

                // Create a new TitleResult object

                TitleResult title = new TitleResult();

				title.TitleResultLink = TitleResultLink;

				title.TitleResultName = TitleResultName;

 

                // Now add the object to my list

                data.Add(title);

             }

 

            ListBox1.Items.AddRange(data.ToArray());           

        }

            

        void listBox1_SelectedIndexChanged(object sender, EventArgs e)

        {

            // Get the name of the selected item

            string item = ListBox1.Items[ListBox1.SelectedIndex].ToString();

            textBox2.Text = item;

      

            foreach (TitleResult d in data)

            {

                if (d.TitleResultName == item)

                {

                    // Save the link in the textbox

                    textBox3.Text = d.TitleResultLink;

                    break;

                }

            }

        }

 

    }

Open in new window

0
 
LVL 1

Author Comment

by:Smyken
ID: 24021632
Hi again 8=)

Sorry to say but I still don't get this to work.
I have no error messages at all or warnings now.

But still only textBox3 is populated with TitleResultLink but textBox2 stays blank all the time.

Any more error checking ?
0
 
LVL 9

Expert Comment

by:djon2003
ID: 24030113
Ehm.. let try out this code which is a little simpler..

I change the struct for a class... Added a ToString function to ensure which attributes should be used as display.

Changed the listBox1_SelectedIndexChanged so it's casting the your object type and you can use it directly.
using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Collections;

using System.Windows.Forms;

using System.Net;

using System.Xml;

using System.IO;

using System.Text.RegularExpressions;

 

 

 

    public partial class Form1 : Form

    {

      

        // All items

        private List<TitleResult> data;

 

        // Struct to save the results

        private class TitleResult

        {

            public string TitleResultLink;

            public string TitleResultName;
 

            public String ToString() {

                   return TitleResultName;

            }

        };

 

        public Form1()

        {

 

            InitializeComponent();

                  

            // Create a new list

            data = new List<TitleResult>();

 

            // Register the event

            listBox1.SelectedIndexChanged += listBox1_SelectedIndexChanged;

            button1.Click += new EventHandler(button1_Click);

 

        }

        

        private void button1_Click(object sender, EventArgs e)

        {

            string Search1 = "http://www.mysite.com/Search.aspx?SearchString=";

            string Search3 = "&media=0";

            string Search2 = textBox1.Text;

            string url = string.Concat(Search1, Search2, Search3);

 

            HttpWebRequest myWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);

            myWebRequest.Method = "GET";

 

            // make request for web page

 

            HttpWebResponse myWebResponse = (HttpWebResponse)myWebRequest.GetResponse();

 

            StreamReader myWebSource = new StreamReader(myWebResponse.GetResponseStream());

 

            string myPageSource = myWebSource.ReadToEnd();

 

            myWebResponse.Close();

 

 

 

            //Strip Spaces etc

            myPageSource = myPageSource.Replace("&amp;", "&").Replace("\r", "").Replace("\n", "").Replace("\t", "").Replace("\"", "").Replace("#", "");

 

 

 

            //Parse the String and get Title and Link

            Regex Itemtitle = new Regex(@"ListItem_ItemTitle><a href=(?<Titlelink>.*?)>(?<Titlename>.*?)</a>");

 

            //Match possible results from Html Page

            Match match;

            for (match = Itemtitle.Match(myPageSource); match.Success; match = match.NextMatch())

            {

 

                string Titlelink = match.Groups["Titlelink"].Value;

                string Titlename = match.Groups["Titlename"].Value;

 

 

                string Mysite_Url = "http://www.mysite.com";

 

                string TitleResultLink = string.Concat(Mysite_Url, Titlelink);

                string TitleResultName = (Titlename);

                                

                // Create a new TitleResult object

                TitleResult title = new TitleResult();

                                title.TitleResultLink = TitleResultLink;

                                title.TitleResultName = TitleResultName;

 

                // Now add the object to my list

                data.Add(title);

             }

 

            ListBox1.Items.AddRange(data.ToArray());           

        }

            

        void listBox1_SelectedIndexChanged(object sender, EventArgs e)

        {

            TitleResult item = ListBox1.Items[ListBox1.SelectedIndex];

            textBox2.Text = item.TitleResultName;

            textBox3.Text = item.TitleResultLink;

        }

 

    }

Open in new window

0
 
LVL 1

Author Comment

by:Smyken
ID: 24030750
Get this errors now instead:

Warning      1      'Form1.TitleResult.ToString()' hides inherited member 'object.ToString()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword.

error points to:
public String ToString(){
                return TitleResultName;
            }



and

Error      2      Cannot implicitly convert type 'object' to 'Form1.TitleResult'. An explicit conversion exists (are you missing a cast?)      

pointing to:

TitleResult item = ListBox1.Items[ListBox1.SelectedIndex];
0
 
LVL 9

Accepted Solution

by:
djon2003 earned 500 total points
ID: 24030890
Excuse me, I wasn't sure if in C# you add to put this keyword.. Here is the new code..

Not all languages require explicit conversion.. So I added the conversion (For error 2).
using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Collections;

using System.Windows.Forms;

using System.Net;

using System.Xml;

using System.IO;

using System.Text.RegularExpressions;

 

 

 

    public partial class Form1 : Form

    {

      

        // All items

        private List<TitleResult> data;

 

        // Struct to save the results

        private class TitleResult

        {

            public string TitleResultLink;

            public string TitleResultName;

 

            public overrides String ToString() {

                   return TitleResultName;

            }

        };

 

        public Form1()

        {

 

            InitializeComponent();

                  

            // Create a new list

            data = new List<TitleResult>();

 

            // Register the event

            listBox1.SelectedIndexChanged += listBox1_SelectedIndexChanged;

            button1.Click += new EventHandler(button1_Click);

 

        }

        

        private void button1_Click(object sender, EventArgs e)

        {

            string Search1 = "http://www.mysite.com/Search.aspx?SearchString=";

            string Search3 = "&media=0";

            string Search2 = textBox1.Text;

            string url = string.Concat(Search1, Search2, Search3);

 

            HttpWebRequest myWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);

            myWebRequest.Method = "GET";

 

            // make request for web page

 

            HttpWebResponse myWebResponse = (HttpWebResponse)myWebRequest.GetResponse();

 

            StreamReader myWebSource = new StreamReader(myWebResponse.GetResponseStream());

 

            string myPageSource = myWebSource.ReadToEnd();

 

            myWebResponse.Close();

 

 

 

            //Strip Spaces etc

            myPageSource = myPageSource.Replace("&amp;", "&").Replace("\r", "").Replace("\n", "").Replace("\t", "").Replace("\"", "").Replace("#", "");

 

 

 

            //Parse the String and get Title and Link

            Regex Itemtitle = new Regex(@"ListItem_ItemTitle><a href=(?<Titlelink>.*?)>(?<Titlename>.*?)</a>");

 

            //Match possible results from Html Page

            Match match;

            for (match = Itemtitle.Match(myPageSource); match.Success; match = match.NextMatch())

            {

 

                string Titlelink = match.Groups["Titlelink"].Value;

                string Titlename = match.Groups["Titlename"].Value;

 

 

                string Mysite_Url = "http://www.mysite.com";

 

                string TitleResultLink = string.Concat(Mysite_Url, Titlelink);

                string TitleResultName = (Titlename);

                                

                // Create a new TitleResult object

                TitleResult title = new TitleResult();

                                title.TitleResultLink = TitleResultLink;

                                title.TitleResultName = TitleResultName;

 

                // Now add the object to my list

                data.Add(title);

             }

 

            ListBox1.Items.AddRange(data.ToArray());           

        }

            

        void listBox1_SelectedIndexChanged(object sender, EventArgs e)

        {

            TitleResult item = (TitleResult)ListBox1.Items[ListBox1.SelectedIndex];

            textBox2.Text = item.TitleResultName;

            textBox3.Text = item.TitleResultLink;

        }

 

    }

Open in new window

0
 
LVL 1

Author Comment

by:Smyken
ID: 24032074
I found 1 error in your post:

overrides should be override

8=)

After I corrected this (all is working as intended) !

Thank You for this hard and long Effort 8=)

All the points to you !
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…

708 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

11 Experts available now in Live!

Get 1:1 Help Now