I am trying to populate a combo box based off of the value member that has been selected from a data grid view.
Here is my code to initialise it
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;
With the following code I use this to find the ID of the pitch from the selected row on the data grid view and it returns the correct pitch ID, as seen through debugging.
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());
Now when I try to use that ID to find the datarow within the pitch table I get an error saying
Table doesn't have a primary key
on this line of code
drPitch = dsCIF2.Tables["Pitch"].Rows.Find(Pitch);
I don't know why I am getting this error, thanks in advance!
Update: The table does have a primary key SQL CODE
create TABLE PITCH
(
PitchID int NOT NULL,
PitchDesc varchar(30) NOT NULL,
CONSTRAINT pkPitchID PRIMARY KEY(PitchID),
)
Turns out I forgot to fill the schema of the table. It works now that I have added the following line of code to the initialisation code
daPitch.FillSchema(dsCIF2, SchemaType.Source, "Pitch");
It now looks like this
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");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.