我收到此错误
未处理的类型' System.InvalidCastException'发生了 在WindowsFormsApplication2.exe中附加信息:无法强制转换 类型对象System.Windows.Forms.Button'输入 ' System.Windows.Forms.WebBrowser'
继承代码
private void button6_Click(object sender, EventArgs e)
{
int counter = 0;
string line;
System.IO.StreamReader file = new System.IO.StreamReader("test.txt");
while ((line = file.ReadLine()) != null)
{
textBox6.Text = "";
textBox5.Text = "";
textBox4.Text = "";
textBox2.Text = "";
textBox6.Text = counter.ToString();
string link = line.ToString() ;
textBox5.Text = link;
// WebRequest req = HttpWebRequest.Create(link);
// req.Method = "GET";
WebBrowser wb = (WebBrowser)sender;
wb.Navigate(link);
wb.Document.ExecCommand("SelectAll", false, null);
wb.Document.ExecCommand("Copy", false, null);
string html = wb.DocumentText;
textBox1.Text = html;
textBox2.Text = Clipboard.GetText();
textBox3.Text = "done";
if (html.Contains("<title>"))
{
string title = ExtractFromString(html, "<title>", "</title>");
textBox4.Text = title;
}
else
{
string title = ExtractFromString(html, "<TITLE>", "</TITLE>");
textBox4.Text = title;
}
wb.Dispose();
createpage(textBox4.Text, textBox2.Text, textBox5.Text);
counter++;
}
file.Close();
textBox3.Text = counter.ToString();
}
}
}
答案 0 :(得分:2)
sender
几乎肯定是Button
(来自函数名称&#34; button6_click&#34;)。
WebBrowser wb = (WebBrowser)sender;
Button
无法投放到WebBrowser
(原因很明显)。在这种情况下,您可能需要按名称引用WebBrowser
控件。
WebBrowser wb = someExistingNamedWebBrowser;
答案 1 :(得分:1)
你的问题在于这一行:
WebBrowser wb = (WebBrowser)sender;
因为这是按钮点击事件,sender
将是Button
。试试这个:
WebBrowser wb = new WebBrowser();
或者,如果表单上已有表格,请参考:
WebBrowser wb = webBrowser1;