0

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

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()

4

1 回答 1

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;
    }
}
于 2013-10-29T20:20:21.130 回答