I have 2 tables student and department, in SQLServer
Departmet: with the Following fields
1. DepartmentID (PrimaryKey, AllowNull=false)
2. DepartmentName (Field, AllowNull=False)
Student: with the Following fields
1. StudentID [PrimaryKey, AllowNull=false]
2. StudentName [Field, AllowNull=False]
3. Department_ID [ForeignKey(Department Table), AllowNull=False]
In
VS.Net Projects's addnewItem i added LINQToSQl class, then drag n drop these 2 tables and It created a datacontext.
1. Now i have a datagridview:
-> datasource is set to
student table
2. I added 2 columns in the datagridview(
AutogenerateColumn= false)
1. Student Name(TextBoxColumn)
-> datapropertyname is the StudentName Field of the Student table
2. Department(Comboboxcolumn)
-> Datasource is the Department table
-> ValueMember : "DepartmentID"(
PrimaryKey of the DepartmentTable)
-> DisplayMember : "DepartmentName"(Field in the Department table)
-> Datapropertyname is the Department_ID field of the Student Table
Code:
DataClasses1DataContext dc = new DataClasses1DataContext();
private void Form1_Load(object sender, EventArgs e)
{
dc.Log = Console.Out;
BindingSource bsDepartment = new BindingSource();
bsDepartment.DataSource = dc.GetTable<DepartmentTable>().GetNewBindingList();
BindingSource bsStudent = new BindingSource();
bsStudent.DataSource = dc.GetTable<StudentTable>().GetNewBindingList();
dgvStaffMaster.AutoGenerateColumns = false;
dgvStaffMaster.DataSource = bsStudent;
DataGridViewTextBoxColumn colName = new DataGridViewTextBoxColumn();
colName.Name = "StudentName";
colName.HeaderText = "Student Name";
colName.DataPropertyName = "StudentName";
dgvStaffMaster.Columns.Add(colName);
DataGridViewComboBoxColumn coldept = new DataGridViewComboBoxColumn();
coldept.Name = "Department_ID";
coldept.HeaderText = "Department";
coldept.DataSource = bsDepartment;
coldept.ValueMember = "DepartmentID";
coldept.DisplayMember = "DepartmentName";
coldept.DataPropertyName = "Department_ID";
dgvStaffMaster.Columns.Add(coldept);
}
private void btnSave_Click(object sender, EventArgs e)
{
dc.SubmitChanges();
}
PROBLEM:
Every thing works fine if i
Edit the Contents of the datagridview,
but if i try to add a
newItem, in the
NewRow of the Datagridiview,
InvalidComboboxCellValue exception is thrown.
But if i set the
AllowNull Property of the
Department_ID field of the student table to
true, Every thing
Works Fine!
3. Department_ID [ForeignKey(Department Table),
AllowNull=True]
But i need the it to be
false, Please Help!
I'm breaking my head for the past one week!
Please Help Me,