Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 441
  • Last Modified:

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

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
Smyken
Asked:
Smyken
  • 8
  • 6
  • 2
1 Solution
 
counterrootCommented:
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
 
SmykenAuthor Commented:
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
 
counterrootCommented:
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
Visualize your virtual and backup environments

Create well-organized and polished visualizations of your virtual and backup environments when planning VMware vSphere, Microsoft Hyper-V or Veeam deployments. It helps you to gain better visibility and valuable business insights.

 
SmykenAuthor Commented:
Sorry but I'm really lost here.
0
 
counterrootCommented:
whats the problem?
0
 
SmykenAuthor Commented:
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
 
counterrootCommented:
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
 
SmykenAuthor Commented:
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
 
counterrootCommented:
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
 
SmykenAuthor Commented:
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
 
counterrootCommented:
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
 
SmykenAuthor Commented:
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
 
djon2003Commented:
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
 
SmykenAuthor Commented:
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
 
djon2003Commented:
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
 
SmykenAuthor Commented:
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: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

  • 8
  • 6
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now