If you are trying to add a new Employee assigned to an existing role, then a better design would be have a dropdown
with all Roles populated instead of a textbox
for user to enter.
The dropdown should get filled with all the Roles from Roles table. (map the SelectedValue
attribute of the dropdown to - RoleId and SelectedText
to RoleName).
When you submit the form, you will get the SelectedValue (RoleId) which you can directly send as part of the INSERT
statement, i.e., dropDownRole.SelectedValue
instead of txtRoleId.Text
Note: Your insert query seems to be a classic candidate for SQL Injection. I suggest you transform it to Parameterized query.
Update: Now that I came to know it is a Winforms application, adding more detailed snippets. Here is how you can do it in the Win Forms world (not as intuitive as web app world though :) ) and please bear with me, it has been years since I had written a winforms snippet.
Define your dropdown combo box like this -
cbxRole.DataSource = roles; // data from back end
cbxRole.Name = "Role";
cbxRole.DropDownStyle = ComboBoxStyle.DropDownList;
cbxRole.DisplayMember = "RoleName"; // should match the property name in your roles data table
cbxRole.ValueMember = "RoleId"; // should match the property name in your roles data table
cbxRole.SelectedItem = null;
cbxRole.SelectedText = "Select Role";
Observe the ValueMember
and DisplayMember
properties. DisplayMember
tells what property in the roles data source to be used to display as the dropdown item text. ValueMember
specifies the property to be used to identify each of the item behind the scenes.
When you submit the details, access the SelectedValue property to get the RoleId corresponding to the selected role name.
private void btnCreate_Click(object sender, EventArgs e)
{
var firstName = txtFirstName.Text;
var lastName = txtLastName.Text;
var roleId = (int)cbxRole.SelectedValue;
}
The SelectedValue
property fetches the value of the column identified by the ValueMember
property in the dropdown definition, which is the RoleId value. Now, you can send this 'roleId' variable's value to the insert query.
here is how it looks like when you submit -

here is quick sample UI -
