组合框选择更改错误 [英] combobox select change error
问题描述
亲爱的所有人,
我要创建一个选择列表项,当我选择黄金项然后在列表中仅显示金项时,当我选择银项然后在列表框中显示唯一的银项时.
我正在使用以下代码,但出现错误将nvarchar值"Gold"转换为数据类型int时转换失败."那么我的代码有什么问题.
Dear All,
I want to create a selection list item when I am select the gold item then show only gold item in the list and when I m select the silver item then it show the only silver item in the list box.
I am using following code but it gives a error "conversion faild when converting the nvarchar value ‘Gold’ to data type int." so what is the problem in my code.
private void cmboItemType() //for combobox
{
string connstr = @"Server=.\SQLEXPRESS ;Initial Catalog=RPSJDB;Integrated Security=True; Max Pool Size=100";
SqlConnection conn = new SqlConnection(connstr);
SqlCommand cmd = new SqlCommand("SELECT * FROM ItemTable", conn);
conn.Open();
SqlDataReader sdr = cmd.ExecuteReader();
ArrayList ItemStore = new ArrayList();
while (sdr.Read())
{
ItemStore.Add(new AddValue(sdr.GetString(1), sdr.GetInt32(0)));
}
sdr.Close();
conn.Close();
cmbItemType.DataSource = ItemStore;
cmbItemType.DisplayMember = "Display";
cmbItemType.ValueMember = "Value";
ItemHaveBeenAdded = true;
}
private void lstboxItem() //for listbox
{
string connstr = @"Server=.\SQLEXPRESS ;Initial Catalog=RPSJDB;Integrated Security=True; Max Pool Size=100";
SqlConnection conn = new SqlConnection(connstr);
this.lstbItem.Items.Clear();
SqlCommand cmd = new SqlCommand
("SELECT * FROM ItemTable Where cmbItemType =" + cmbItemType.SelectedValue, conn);
conn.Open();
SqlDataReader sdrItem = cmd.ExecuteReader();
while (sdrItem.Read())
{
this.lstbItem.Items.Add(sdrItem.GetString(1));
}
sdrItem.Close();
conn.Close();
}
private void cmbItemType_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.ItemHaveBeenAdded)
lstboxItem();
}
public class AddValue
{
private string Displaym;
private long Valm;
public AddValue(string Display, long Value)
{
Displaym = Display;
Valm = Value;
}
public string Display
{
get { return Displaym; }
}
public long Value
{
get { return Valm; }
}
}
推荐答案
避免使用如下代码:
sdr.GetString(1), sdr.GetInt32(0)
用于使用数据读取器读取的数据,因此很难维护.如果您在近期或将来对列顺序进行了任何更改,则还需要更新sdr.GetString(###)
和类似结构中使用的所有索引.
可以使用SELECT
子句中的显式列名(和顺序)来缓解这种情况.
尝试使用
for using the data read by the datareader, it is hard to maintain. If you make any change in column ordering at any near/far future you will also need to update all the indexes used in sdr.GetString(###)
and similar constructs.
This can be mitigated using explicit column names (and ordering) in the SELECT
clause.
Try using
myInt32Data = (Int32)srd["put here the name of the column"]
(此处仅以Int32
为例).这也将有助于调试查询结果.
(Int32
is just used as an example here). This will also help debugging query results.
这篇关于组合框选择更改错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!