1

我有从 SQL 服务器提取信息并显示有关汽车的信息的代码。

问题是数据显示但重复。SQL 数据没有重复,但列表框两次显示相同的数据。

代码如下:

private void Show_Click(object sender, EventArgs e)
        {
            SqlConnection conn = new SqlConnection("Data Source=XXXX");
            DataTable dt = new DataTable();
            SqlDataAdapter SDA = new SqlDataAdapter("SELECT Number_Plate,Registered_Keeper,Make,Model,Year_Of_Make,Colour,Engine_Size,Transmission,Fuel_Type FROM datatable WHERE Number_Plate like '%" + label1.Text + "%'", conn);
            SDA.Fill(dt);
            if (SDA.Fill(dt) == 0)
            {

                button5.Visible = false;
                button4.Visible = true;
                label11.Visible = true;
                Show.Visible = false;
                button3.Visible = true;
                Make.Visible = false;
                Model.Visible = false;
                Year_Of_Make.Visible = false;
                Colour.Visible = false;
                Engine_Size.Visible = false;
                Transmission.Visible = false;
                Fuel_Type.Visible = false;
                Registered_Keeper.Visible = false;
                Plate.Visible = false;
                label2.Visible = false;
                label3.Visible = false;
                label4.Visible = false;
                label5.Visible = false;
                label6.Visible = false;
                label7.Visible = false;
                label8.Visible = false;
                label9.Visible = false;
                label12.Visible = false;
            }
            else
            {
                Plate.DataSource = dt;
                Plate.DisplayMember = "Number_Plate";

                Make.DataSource = dt;
                Make.DisplayMember = "Make";

                Model.DataSource = dt;
                Model.DisplayMember = "Model";

                Year_Of_Make.DataSource = dt;
                Year_Of_Make.DisplayMember = "Year_Of_Make";

                Colour.DataSource = dt;
                Colour.DisplayMember = "Colour";

                Engine_Size.DataSource = dt;
                Engine_Size.DisplayMember = "Engine_Size";

                Transmission.DataSource = dt;
                Transmission.DisplayMember = "Transmission";

                Fuel_Type.DataSource = dt;
                Fuel_Type.DisplayMember = "Fuel_Type";

                Registered_Keeper.DataSource = dt;
                Registered_Keeper.DisplayMember = "RegIstered_Keeper";

                Show.Visible = false;
                button3.Visible = true;
            }

        }

注意:当我在 SQL 中添加数据时,主键缺少大约 20 个数字,所以我的数据是 20 辆汽车,但是当我添加一个新的时,它的主键大约是 50。

4

3 回答 3

3

好吧,你做SDA.Fill(dt)两次。尝试删除 if 之前的行。

...
SqlDataAdapter SDA = ...
if (SDA.Fill(dt) == 0)
...
于 2013-03-19T21:05:11.853 回答
1

你调用SDA.Fill(dt);了两次,一次在外面,一次在 if 语句里面,

于 2013-03-19T21:05:43.070 回答
1

SDA.Fill(dt) 被调用了 2 次,尝试将其更改为 dt.count < 1

于 2013-03-19T21:10:13.147 回答