我试图在组合框中设置值,但每次我尝试这样我都会得到结果' null'。我是否定义了错误的价值,或者我是否试图以错误的方式获得价值?
// Setting the value
sqlCmd.CommandText = "SELECT Id, Ime FROM Unajmljivaci WHERE Aktivan = 0";
conn.Open();
using (var reader = sqlCmd.ExecuteReader())
{
while (reader.Read())
{
cmbUnajmljivaci.Items.Add(new { Id = reader["Id"].ToString(), Ime = reader["Ime"].ToString() });
}
cmbUnajmljivaci.ValueMember = "Id"; // <---
cmbUnajmljivaci.DisplayMember = "Ime";
}
//Retrieving the value
sqlCmd.Parameters.AddWithValue("@SifraUnajmljivca", Convert.ToString(cmbUnajmljivaci.SelectedValue));
答案 0 :(得分:0)
您需要设置组合框的数据源。
答案 1 :(得分:0)
using (SqlConnection sqlConn = new SqlConnection("CONNECTION STRING"))
{
DataSet ds = new DataSet();
SqlCommand sqlCmd = sqlConn.CreateCommand();
sqlConn.Open();
SqlDataAdapter SQA_DataAdapter = new SqlDataAdapter(sqlCmd);
SQA_DataAdapter.SelectCommand = new SqlCommand("SELECT Id, Ime FROM Unajmljivaci WHERE Aktivan = 0", sqlConn);
SQA_DataAdapter.Fill(ds, "Table");
if (ds != null)
if (ds .Tables.Count > 0)
{
cmbUnajmljivaci.ValueMember = "Id";
cmbUnajmljivaci.DisplayMember = "Ime";
cmbUnajmljivaci.DataSource = ds.Tables[0];
}
sqlConn.Close();
}
答案 2 :(得分:0)
尝试获取这样的值:
dynamic dyn = cmbUnajmljivaci.SelectedItem;
string s = dyn.Id;
甚至可以像这样内联:
//Retrieving the value
sqlCmd.Parameters.AddWithValue("@SifraUnajmljivca", Convert.ToString(((dynamic)cmbUnajmljivaci.SelectedItem).Id);
答案 3 :(得分:0)
参考问题的示例代码,
DataSet ds = new DataSet();
DataTable dt = ds.Tables.Add();
dt.Columns.Add("ID");
dt.Columns.Add("Name");
dt.Rows.Add("0", "Item1");
dt.Rows.Add("1", "Item2");
要插入具有指定索引的项目,您需要使用以下代码
//Insert the item into the collection with specified index
foreach (DataRow row in dt.Rows)
{
int id = Convert.ToInt32(row["ID"]);
string name=row["Name"].ToString();
comboBox1.Items.Insert(id,name);
}
始终索引应该从 0(零)开始。
简单方法为组合框添加值
comboBox1.DataSource=dt;
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "ID";