0

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

我尝试了一切,例如:

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

}
4

1 回答 1

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;
        }
于 2013-01-08T10:12:52.743 回答