无法将类型'object'隐式转换为'string'。存在显式转换(您是否错过了演员?) [英] Cannot implicitly convert type 'object' to 'string'. An explicit conversion exists (are you missing a cast?)

查看:343
本文介绍了无法将类型'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
           }
     }

推荐答案

[更新]

错误的原因是 DataRow 的类型为 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; 
           }
     }


这篇关于无法将类型'object'隐式转换为'string'。存在显式转换(您是否错过了演员?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆