且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

无法将类型'object'隐式转换为'string'。存在显式转换(您是否错过了演员?)

更新时间:2023-02-13 08:22:25

[更新]

错误的原因是 DataRow $ c中的单元格$ c>的类型为 object ,您将其视为字符串

因此,你需要将对象转换为字符串。

[]



简单的解决方案是

[Updated]
The reason for the error is that a cell in a DataRow is of type object and you treat it as it would be a string.
Hence, you need to convert the object to a string.
[]

The simple solution is
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


你可以这样试试



you can try like this

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; 
           }
     }