让用户设置自己的主页无法正常工作

时间:2013-10-29 20:10:02

标签: c# winforms httpwebrequest

基本上,我有两种形式。 Home是在单击主窗体中的菜单项时创建的窗体。菜单项弹出此表单,要求用户将所需的URL作为他/她的主页。还包含“确定”和“取消”按钮。该URL应保存在字符串中,以便在按下主页按钮时可以从Form1访问它。主页按钮应加载保存在richTextBox中的URL。我在调用httpwebrequest.create(string URLSavedInHomepage)

时收到错误消息,说我的URI无效
public partial class Home:Form
{
    //string homeURL = "";
    string homepage;
    public Home()
    {
        InitializeComponent();
    }


    private void OKButton_Click(object sender, EventArgs e)
    {
        string currentInput = url.Text;
        homepage = "http://" + currentInput;
        setHomepage(homepage);
        this.Close();
    }


    private void CancelB_Click_1(object sender, EventArgs e)
    {
        this.Close();
    }

    public string getHomepage()
    {
        return homepage;
    }
    public void setHomepage(string home)
    {
        homepage = home;
    }

    private void Home_Load(object sender, EventArgs e)
    {
        string currentInput = url.Text;
        homepage = "http://" + currentInput;
        setHomepage(homepage);
    }

主表单中的一些代码:

private void HomePage_Click(object sender, EventArgs e)
    {
        Home home = new Home();
        URLInput.Text = home.getHomepage();
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URLInput.Text);
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        StreamReader sr = new StreamReader(response.GetResponseStream());
        richTextBox1.Text = sr.ReadToEnd();

    }
private void ChangeHomeToolStripMenuItem_Click(object sender, EventArgs e)
//this is menu item to call 
    {
        Home h = new Home();
        h.Show();
    }

注意,我不能使用WebBrowser类,因为要求说我不能使用它,否则我只使用.Navigate()

1 个答案:

答案 0 :(得分:0)

按如下方式更改代码(我假设URLInput是主窗体上的控件):

private void HomePage_Click(object sender, EventArgs e)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URLInput.Text);
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    StreamReader sr = new StreamReader(response.GetResponseStream());
    richTextBox1.Text = sr.ReadToEnd();
}

private void ChangeHomeToolStripMenuItem_Click(object sender, EventArgs e)
//this is menu item to call 
{
    using(Home h = new Home())
    {
        h.ShowDialog();
        var homePageUrl = h.getHomePage();
        if (string.IsNullOrEmpty(homePageUrl))
            return;
        URLInput.Text = homePageUrl;
    }
}