如何滚动到listBox中的选定项?

时间:2013-01-07 23:01:54

标签: c# wpf

我正在使用存储过程添加客户。 我以某种方式设法在插入后选择新添加的客户,但我不能专注于列表框中的记录..

我尝试了一切,比如:

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; }
    }

}

1 个答案:

答案 0 :(得分:0)

将您的代码更改为:

        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;
        }