user2911539 user2911539 - 24 days ago 7
ASP.NET (C#) Question

Connecting Two SQL Server Tables

I'm trying to connect the following 2 tables together:

CREATE TABLE [dbo].[Groups]
(
[Group_Id] INT IDENTITY (1, 1) NOT NULL,
[Group_Name] NVARCHAR (50) NULL,
[Group_Desc] NVARCHAR (50) NULL,

PRIMARY KEY CLUSTERED ([Group_Id] ASC)
);

CREATE TABLE [dbo].[Events]
(
[Event_Id] INT IDENTITY (1, 1) NOT NULL,
[Event_Group_Id] INT null,
[Event_Type] NVARCHAR (50) NULL,
[Event_Title] NVARCHAR (50) NULL,

PRIMARY KEY CLUSTERED ([Event_Id] ASC),

CONSTRAINT fk_event_group
FOREIGN KEY (Event_Group_Id) REFERENCES Groups (Group_Id)
);


First question: have I created the tables correctly?

I've been able to add to the
Events
with the following code but I haven't been able to successfully connect the PK of
Groups
as an FK in
Events
.

Does anyone have any suggestions?

SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["BallinoraDBConnectionString1"].ConnectionString);
conn.Open();
string findGroupOfEvent = "SELECT Group_Id FROM Groups WHERE Group_Name ='" + DropDownListEventGroup.SelectedItem.ToString() + "'";
int groupId = Convert.ToInt32(findGroupOfEvent);
string insertQuery = "INSERT INTO Events (Event_Group_Id, Event_Type, Event_Title) VALUES (@GroupEventID, @Type, @Title)";
SqlCommand com = new SqlCommand(insertQuery, conn);
com.Parameters.AddWithValue("@GroupEventID", groupId);
com.Parameters.AddWithValue("@Type", DropDownListEventType.SelectedItem.ToString());
com.Parameters.AddWithValue("@Title", TextBoxET.Text);
com.ExecuteNonQuery();
Response.Redirect("ViewEvents.aspx");
Response.Write("Registration is successful");
conn.Close();


UI

Adding Dropdown Items

Answer

Change the value in your designer screen shot https://i.stack.imgur.com/c0Ryz.png to 1 and then 2 etc that corresponds to the ids you used in your database table. That is why your code is failing as you cannot convert a string name to an integer. The value is the unique id (int), the name is the display text.

A much better and more maintainable option would be to dynamically generate the list items from the database values when the form/control loads. There are many already asked questions with good answers on this like Databind ASP.NET List of ListItem to DropDownList issue