I'm very new to C#, but doing some experiments on my own. I created a Database with 3 tables:
tbl_Student: IDCard, Sname, Ssurname
tbl_Course: CID, Cname
tbl_StudentClass: CID, IDCard.
There is a relationship between them. Database part I'm OK.
Now I created 2 forms. 1 Form fills the Course table. The other Form fills the Student table. In the Student Form, I have a combobox that lists the CourseName, reading from the Course Table. The Combobox is working fine.
The problem is that when I want to click the SAVE button, the StudentCourse table is filled using the IDCard and the CID according to what course the user choose from the combobox dropdown. I can fill the IDCard but don't know how to fill the CID, that is use the CID of the Course Name selected from the combobox....any help please?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace StudentClassApplication
{
public partial class frmCreateStudent : Form
{
SqlConnection con = new SqlConnection(@"Data Source=REUBEN-PC\MSSQLEXPRESS;Initial Catalog=StudentClass;Integrated Security=True");
public frmCreateStudent()
{
InitializeComponent();
FillCombobox();
}
private void SaveStudent_button1_Click(object sender, EventArgs e)
{
try
{
con.Open();
SqlCommand cmd1 = new SqlCommand("INSERT into tbl_Student (IDCard,Sname, Ssurname) values (@IDCard,@Sname,@Ssurname)", con);
cmd1.Parameters.AddWithValue("@IDCard", textBox1.Text);
cmd1.Parameters.AddWithValue("@Sname", textBox2.Text);
cmd1.Parameters.AddWithValue("@Ssurname", textBox3.Text);
cmd1.ExecuteNonQuery();
cmd1.Parameters.Clear();
SqlCommand cmd2 = new SqlCommand("INSERT into tbl_StudentClass (IDCard, CID) VALUES (@IDCard,@CID)", con);
cmd2.Parameters.AddWithValue("@IDCard", textBox1.Text);
cmd2.Parameters.AddWithValue("@CID", comboBox1.SelectedValue);
cmd2.ExecuteNonQuery();
cmd2.Parameters.Clear();
con.Close();
MessageBox.Show("Student has been added ! ");
}
catch (Exception ex)
{
MessageBox.Show("Cannot open connection ! ");
}
}
private void frmCreateStudent_Load(object sender, EventArgs e)
{
}
public void FillCombobox()
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = ("select * from tbl_Class");
SqlDataReader myreader;
try
{
con.Open();
myreader = cmd.ExecuteReader();
while (myreader.Read())
{
string cname = myreader.GetString(1);
comboBox1.Items.Add(cname);
}
}
catch (Exception ex)
{
MessageBox.Show("Cannot open connection ! ");
}
}
protected void comboBox1_DataBound(object sender, EventArgs e)
{
var value = comboBox1.SelectedValue;
}
}
}
What I have tried:
I have tried this code, but not working.