将2 listBox中的项添加到一个listBox

时间:2013-08-24 12:18:35

标签: c# .net webrequest

您好我如何将2个listBox中的项目添加到一个listBox

例如: listBox1包含Hello listBox2包含世界! 因此,如果在listbox3中单击button1将显示Hello World!再见,但不是像

这样的新行

您好

世界!

    private void button2_Click(object sender, EventArgs e)
    {
      listBox3.Items.Add(listBox1.Items + listBox2.Items);
    }

以及另外1个如何从2 listBox.items

制作HttpWebRequest
    private void button1_Click(object sender, EventArgs e)
    {
        WebRequest request = WebRequest.Create(listBox1.Items + listBox2.Items);
    }

例如: listBox1包含http://test.com listBox2包含/index.html 因此,如果单击button1,它会将listBox1和listBox2中的项组合成1项 因此它将成为http://test.com/index.html并将请求发送到网站

还有1个为什么这个代码在catch(WebException x)

处停止

为什么返回false;当button1_click处于无效状态时不工作,我尝试将按钮设置为bool类型,但它会使listBox1出错。

    private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            for (int i = 0; i < listBox1.Items.Count; i++)
            {
                // Create a request for the URL.        
                WebRequest request = WebRequest.Create(listBox1.Items[i].ToString());
                // If required by the server, set the credentials.
                request.Credentials = CredentialCache.DefaultCredentials;
                // Get the response.
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                // Display the status.
                // Get the stream containing content returned by the server.
                Stream dataStream = response.GetResponseStream();
                // Open the stream using a StreamReader for easy access.
                StreamReader reader = new StreamReader(dataStream);
                // Read the content. 
                string responseFromServer = reader.ReadToEnd();
                // Display the content.
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    listBox2.Items.Add(listBox1.Items[i]);
                }
                // Cleanup the streams and the response.
                reader.Close();
                dataStream.Close();
                response.Close();
            }

            }
        catch (WebException x)
        {
            listBox2.Items.Add("Error! " + x.Message);
        } 
    }

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

第一部分:

listbox3.items.add(listbox1.SelectedItem.ToString() + listbox2.SelectedItem.ToString());

第二部分:

WebRequest request = WebRequest.Create(listBox1.SelectedItem.ToString() +   
listBox2.SelectedItem.ToString());

最后阶段:

If exception occurs and different url is expected then do select different url entries    
from both listbox1 and listbox2 and click the button to check. Also keep correct 
entries in both the listboxes to avoid exception.

答案 1 :(得分:0)

  1. 从ListBox中获取所选项:ListBox1.SectedItem
  2. 连接字符串:string1 + string2
  3. 将项目添加到ListBox:ListBox1.Items.Add(“item_name_or_value”)