如何滚动到列表框中的选定项目
本文关键字:项目 列表 何滚动 滚动 | 更新日期: 2023-09-27 17:50:53
我正在使用存储过程添加一个Customer。在插入后,我设法选择了新添加的客户,但是我无法关注listbox中的记录.
我试了所有的方法,比如:
lbxCustomers.ScrollIntoView(this.lbxCustomers.SelectedIndex);
和许多修改使用项目和东西,但没有工作。它仍然没有滚动视图到选定项目。什么好主意吗?
WPF。
我的init是这样的:
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;
}