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
426 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
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 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
 
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

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…
In an interesting question (https://www.experts-exchange.com/questions/29008360/) here at Experts Exchange, a member asked how to split a single image into multiple images. The primary usage for this is to place many photographs on a flatbed scanner…

828 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