本文介绍了无法将类型'object'隐式转换为'string'。存在显式转换(您是否错过了演员?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
DataSet1TableAdapters.TextBoxTableTableAdapter tx;
tx = new DataSet1TableAdapters.TextBoxTableTableAdapter();
DataTable dt = new DataTable();
dt = tx.GetstudData(int.Parse(DropDownList1.SelectedValue));
foreach (DataRow row in dt.Rows)
{
TextBox1.Text = (row["FirstName"]); // error shown here
TextBox2.Text = (row["SecondName"]); // error shown here
}
}
推荐答案
TextBox1.Text = row["FirstName"].ToString();
但是,如果 DataRow
单元格中的值为null,您将得到一个空指针错误。
为避免这样做,你可以这样做:
However, if the value in the DataRow
cell is null, you will get a null pointer error.
To avoid that you can do like this:
if (row["FirstName"] != null)
TextBox1.Text = row["FirstName"].ToString();
else
TextBox1.Text = ""; // Or what is suitable
或
or
TextBox1.Text = (row["FirstName"] != null) ? row["FirstName"].ToString() : "";
如果你确定你的 DataRow
单元格包含一个字符串,你可以做显式类型案例
If you are sure your DataRow
cell contains a string, you can do an explicit type case
TextBox1.Text = (string)row["FirstName"];
但如果单元格的值为null,这也会导致问题,如果单元格的数据类型不是 string 。
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
DataSet1TableAdapters.TextBoxTableTableAdapter tx;
tx = new DataSet1TableAdapters.TextBoxTableTableAdapter();
DataTable dt = new DataTable();
dt = tx.GetstudData(int.Parse(DropDownList1.SelectedValue));
foreach (DataRow row in dt.Rows)
{
TextBox1.Text = (row["FirstName"]) as string;
TextBox2.Text = (row["SecondName"]) as string;
}
}
这篇关于无法将类型'object'隐式转换为'string'。存在显式转换(您是否错过了演员?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!