谁能帮我看一下代码,为什么会出错?

govictory 2009-03-15 02:11:33
下面的程序运行的时候,黄色部分代码为什么总是运行不过去,提示“无法将类型为“System.String”的对象强制转换为类型“WindowsApplication1.PDSAListItemNumeric””?


namespace WindowsApplication1
{
public partial class frmProducts : Form
{
public frmProducts()
{
InitializeComponent();
}

private void frmProducts_Load(object sender, EventArgs e)
{
ListLoad();
}
private void ListLoad()
{
SqlCommand oCmd;
SqlDataReader oDR;
string strSQL;
string strConn;
//PDSAListItemNumeric oItem;
strConn = ConnectStringBuild();

strSQL = "SELECT ProductID,ProductName FROM Products";
//strSQL += "";

try
{
oCmd = new SqlCommand();
oCmd.Connection = new SqlConnection(strConn);
oCmd.Connection.Open();
oCmd.CommandText = strSQL;
oDR = oCmd.ExecuteReader();
lstProducts.Items.Clear();
while (oDR.Read())
{
lstProducts.Items.Add(oDR["ProductID"].ToString());
}

{
lstProducts.SetSelected(0, true);
}
}
catch (Exception oExcept)
{
MessageBox.Show(oExcept.Message);
}
}
private string ConnectStringBuild()
{
string strConn;
strConn = "Data Source=(local);";
strConn += "Initial Catalog=pro;";
strConn += "User ID=sa;";
strConn += "Password=1234;";
return strConn;
}
private void FormShow()
{
SqlCommand oCmd;
SqlDataReader oDR;
PDSAListItemNumeric oItem;
string strSQL;
string strConn;
strConn = ConnectStringBuild();
oItem = (PDSAListItemNumeric) lstProducts.SelectedItem;
strSQL = "SELECT ProductID,ProductName FROM Products";
strSQL += "WHERE ProductID=" + oItem.ID;
try
{
oCmd = new SqlCommand();
oCmd.Connection = new SqlConnection(strConn);
oCmd.Connection.Open();
oCmd.CommandText = strSQL;
oDR = oCmd.ExecuteReader();
if (oDR.Read())
{
textBox1.Text = oDR["ProductID"].ToString();
textBox2.Text = oDR["ProductName"].ToString();
}
oDR.Close();
oCmd.Connection.Close();
}
catch (Exception oException)
{
MessageBox.Show(oException.Message);
}
}

private void lstProducts_SelectedIndexChanged(object sender, EventArgs e)
{
FormShow();
}
}

}
...全文
120 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
govictory 2009-03-15
  • 打赏
  • 举报
回复
那应该怎么转换呢?我新学的还不太懂,别见笑哦
ojekleen 2009-03-15
  • 打赏
  • 举报
回复
lstProducts.SelectedItem 是字符串,不能强制转换成PDSAListItemNumeric


类型转换的错误自己看看就明白了
govictory 2009-03-15
  • 打赏
  • 举报
回复
另外,我的PDSAListItemNumeric类是这样写的,是不是有错呢?

namespace WindowsApplication1
{
class PDSAListItemNumeric
{
private string mstrValue;
private int mintID;
public PDSAListItemNumeric()
{


}
public PDSAListItemNumeric(string strValue, int intID)
{
mstrValue = strValue;
mintID = intID;
}
public string value
{
get
{
return mstrValue;
}
set
{
mstrValue = value;
}
}
public int ID
{
get
{
return mintID;
}
set
{
mintID = value;
}
}
public override string ToString()
{
return mstrValue;
}
}
}

111,126

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧