"表格不包含主键"

时间:2018-04-10 09:02:05

标签: c# sql-server

我正在尝试根据从数据网格视图中选择的值成员填充组合框。

这是我的初始化代码

            DataSet dsCIF2 = new DataSet();
            DataRow drPitch;
            String sqlPitch = @" Select * from Pitch";
            String connStr5 = Properties.Resources.cString;
            SqlDataAdapter daPitch = new SqlDataAdapter(sqlPitch, connStr5);
            DataTable dtPitch = new DataTable();
            daPitch.Fill(dtPitch);
            daPitch.Fill(dsCIF2, "Pitch");

            comboBox2.DisplayMember = "PitchDesc";
            comboBox2.ValueMember = "PitchID";
            comboBox2.DataSource = dtPitch;

使用以下代码,我使用它来从数据网格视图中的所选行中查找音高的ID,并返回正确的音高ID,如调试所示。

 int matchBookingID = 0;
            matchBookingID = Convert.ToInt32(DGV.SelectedRows[0].Cells[0].Value);
            drMatchData = dsCIF.Tables["MatchStats"].Rows.Find(matchBookingID);
                Pitch = Convert.ToInt32(drMatchData["PitchID"].ToString());

现在,当我尝试使用该ID在音高表中找到数据行时,我收到错误

表格没有主键

在这行代码上

                drPitch = dsCIF2.Tables["Pitch"].Rows.Find(Pitch);

我不知道为什么我会收到此错误,提前谢谢!

更新:该表有一个主键 SQL CODE

create TABLE PITCH
(
PitchID int NOT NULL,
PitchDesc varchar(30) NOT NULL,
CONSTRAINT pkPitchID PRIMARY KEY(PitchID),
)

1 个答案:

答案 0 :(得分:2)

原来我忘了填写表的架构。现在我已经将以下代码行添加到初始化代码

daPitch.FillSchema(dsCIF2, SchemaType.Source, "Pitch");

现在看起来像这样

DataSet dsCIF2 = new DataSet();

String sqlPitch = @" Select * from Pitch";
String connStr5 = Properties.Resources.cString;
SqlDataAdapter daPitch = new SqlDataAdapter(sqlPitch, connStr5);
SqlCommandBuilder cmdBPitch = new SqlCommandBuilder(daPitch);

daPitch.FillSchema(dsCIF2, SchemaType.Source, "Pitch");

DataTable dtPitch = new DataTable();
daPitch.Fill(dtPitch);
daPitch.Fill(dsCIF2, "Pitch");