[英]How to scroll to selected item in listBox?
我正在使用存儲過程添加客戶。 插入后,我設法以某種方式選擇了新添加的客戶,但是我無法專注於列表框中的記錄。
我嘗試了一切,例如:
lbxCustomers.ScrollIntoView(this.lbxCustomers.SelectedIndex);
以及使用“物品”和“東西”進行的許多修改,但沒有任何效果。 它仍然沒有將視圖滾動到所選項目。
是WPF。
我的初始化看起來像這樣:
private void init()
{
SqlConnection connection = null;
SqlDataReader reader = null;
try
{
connection = new SqlConnection(this.strConnection);
connection.Open();
SqlCommand command = new SqlCommand("SELECT CustomerID, CompanyName, ContactName FROM Customers", connection);
SqlDataAdapter sda = new SqlDataAdapter(command);
reader = command.ExecuteReader();
ListItem listItem;
while (reader.Read())
{
listItem = new ListItem(reader.GetValue(0).ToString(), reader.GetValue(1).ToString(), reader.GetValue(2).ToString());
this.lbxCustomers.Items.Add(listItem);
}
}
catch (Exception e)
{
MessageBox.Show(e.Message, "Error", MessageBoxButton.OKCancel, MessageBoxImage.Exclamation);
}
finally
{
connection.Close();
reader.Close();
}
}
init2相同,除了以下行:
SqlCommand command = new SqlCommand("SELECT CustomerID, CompanyName, ContactName FROM Customers WHERE CompanyName = '" + correctID + "'", connection);
它引用如下所示的ListItem:
class ListItem
{
private string customerID, companyName, contactName;
public ListItem(string customerID, string companyName, string contactName)
{
this.customerID = customerID.Replace("'", "''");
this.companyName = companyName.Replace("'", "''");
this.contactName = contactName.Replace("'", "''");
}
public override string ToString()
{
return this.companyName + " (" + this.contactName + ")";
}
public string CustomerID
{
get { return this.customerID; }
}
}
將您的代碼更改為:
ListItem listItem = null;
while (reader.Read())
{
listItem = new ListItem(reader.GetValue(0).ToString(), reader.GetValue(1).ToString(), reader.GetValue(2).ToString());
this.lbxCustomers.Items.Add(listItem);,
lbxCustomers.SelectedItem = listItem;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.