[英]Selected item in list box keeps returning null
我正在嘗試從我的列表框中 select 給定數字但是當我運行代碼時它返回 null
我試過了。selectedvalue 我試過了。selecteditem 和 .selecteditems 都返回 null
ID = ExpireditemInfo.GetItemText(ExpireditemInfo.SelectedItem);
ID 是一個字符串
這是我使用 dapper 的來源
loadinventory = iteminfo.GetExpireinfo(now,expirationDate);
ExpirationID.DataSource = loadinventory;
ExpirationID.DisplayMember = "Expireing_ID";
我的數據 model
public string Transaction_ID { get; set; }
public string Type_Of_Transaction { get; set; }
public string Name { get; set; }
public string Quantity { get; set; }
public string Unit { get; set; }
public string Expireing_ID
{
get
{
return $"{Transaction_ID}";
}
}
我想 select 列表框等中的數字 6 並將該選擇存儲在一個字符串中,然后我將其轉換為 int 以通過存儲過程傳遞。 int 用於數據庫的 id 列,因此在傳遞到數據庫時它必須是 in。
是不是 6 沒有被識別為字符串,如果是這樣,我該怎么辦 select 呢?
我正在嘗試從我的列表框中 select 給定數字但是當我運行代碼時它返回 null
在看到您綁定到ListBox
的方式后,您似乎沒有設置ValueMember
屬性,這樣做您可以擁有一個實際的DisplayMember
和一個ValueMember
來表示該顯示器 object 的實際基礎值。
這就是我要做的,這只是一個例子:
// Holds the actual selected items value
public string ExpirationIDValue {get; private set;}
// Anytime the selected index changes, we update our property. You can
// put this on the constructor and or on load.
ExpirationID.SelectedIndexChanged += ExpirationID_SelectedIndexChanged;
// Event handler for when selection changes
private void ExpirationID_SelectedIndexChanged(object sender, EventArgs e)
{
if (sender is ListBox listBox && listBox.SelectedValue != null)
{
ExpirationIDValue = listBox.SelectedValue.ToString();
}
}
// This was for testing, just to get some data, you can ignore this
DataTable dataTable = new DataTable();
dataTable.Columns.Add(new DataColumn("Expireing_ID",typeof(string)));
dataTable.Columns.Add(new DataColumn("Expireing_ID_Display",typeof(string)));
int i = 1;
while(i < 10)
{
dataTable.Rows.Add(i.ToString(),$"Display {i}");
i++;
}
// Here you need to make sure you set these properties to your actual
// property names.
ExpirationID.DataSource = dataTable;
ExpirationID.DisplayMember = "Expireing_ID_Display";
ExpirationID.ValueMember = "Expireing_ID";
注意:您的 selectedindexchanged 事件可能會提前觸發並導致異常,您可以做的是創建一個變量 bool 並在加載時將其設置為 true,然后在事件中確保它不是 true。 在加載數據結束時,將其設置回 false。
希望這能解決您的問題,如果您有什么不明白或需要進一步說明,請告訴我。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.