在C#中将组合框字符串值转换为int并在SQL Server DB中传递值

时间:2017-01-10 16:51:50

标签: c# sql sql-server sql-server-2014

我希望我能用编程清楚地解释我的困境。我在编程方面相当新,所以请耐心等待。我正在使用C#和SQL Server 2014.

我在SQL Server中创建了一个名为Roles和AccountRegistration的表:

Roles Table具有RoleId(pk)和RoleName while AccountRegistration表具有用户名(pk),密码,RoleId(fk),FullName,Address。

两个表都通过RoleID

相关联

现在,我创建了一个帐户注册表单(C#),其中包含用户名,密码,全名,地址和角色名称。

RoleName在组合框中,如果用户选择Admin或Employee,如何将其转换为int,以便将其传递给RoleId字段?

这是我尝试过的(仅使用SQL Server),但它不起作用。

INSERT INTO AccountRegistration(RoleID)
SELECT a.RoleName
FROM Roles a
INNER JOIN AccountRegistration b ON cast(a.RoleId as nvarchar(255))=b.RoleID

错误消息:

  

Msg 245,Level 16,State 1,Line 1

     

转换nvarchar值时转换失败'管理员'数据类型int。

我还没有尝试用C#编码,因为我还在试图找出逻辑。

SqlConnection con = new SqlConnection(@"Data Source=***\sqlexpress;Initial Catalog=****;User ID=**;Password=****");


        public FrmAddNewAccount()
        {
            InitializeComponent();
        }

        private void FrmAddNewAccount_Load(object sender, EventArgs e)
        {
            SqlDataAdapter sqlDataAdapter = new SqlDataAdapter("Select * From Roles", con);
            DataSet dataSet = new DataSet();
            sqlDataAdapter.Fill(dataSet);
            cmbRole.DisplayMember = "RoleName";
            cmbRole.ValueMember = "RoleId";
            cmbRole.DataSource = dataSet;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            con.Open();
            SqlDataAdapter sda = new SqlDataAdapter("Insert into AccountRegistration(Username, Password, RoleID, FullName, Address) VALUES ('" + txtUsername.Text + "', '" + txtPassword.Text + "', '" + cmbRole.Text + "', '" + txtFullName.Text +"', '"+txtAddress.Text+"')", con);
            sda.SelectCommand.ExecuteNonQuery();
            con.Close();
        }


        private void cmbRole_SelectedValueChanged(object sender, EventArgs e)
        {
            string RoleId = cmbRole.SelectedValue.ToString();

        }

3 个答案:

答案 0 :(得分:1)

您必须将RoleId和RoleName绑定到组合框。

<?php
require "conn.php";

$email = $_POST["email"];
$password = $_POST["password"];

$mysql_qry = "INSERT INTO users (email, password) VALUES ('$email','$password')";

if($conn->query($mysql_qry) === TRUE){
echo "Insert successful";
} else {
echo "Insert failed, please try again.";
}
$conn->close();
?>

当在ComboBox中选择了项目时,必须将selectedValue作为RoleId发送到t-sql用于在表格中插入

 SqlConnection sqlConnection=new SqlConnection("Your Sql Server Connection");
            SqlDataAdapter sqlDataAdapter=new SqlDataAdapter("Select * From Roles",sqlConnection);
            DataSet dataSet = new DataSet();
            sqlDataAdapter.Fill(dataSet);
            comboBoxRoles.DisplayMember = "RoleName";
            comboBoxRoles.ValueMember = "RoleId";
            comboBoxRoles.DataSource = dataSet;

答案 1 :(得分:0)

这实际上是一个SQL问题。它不起作用的原因是因为&#39; Admin&#39;不是一个数字。您在C#中需要做的事情是这样的(我将让您编写从SQL Server实际读取的代码):

string[] positionTypes = new String { "admin", "manager", "peon" }; //fill the array with your positions.
public static int ConvertFromPosition(string pos)
{
       return positionTypes.IndexOf(pos.ToLower().Trim());
}

对于您提供给我们的信息,这只是一个快速而肮脏的问题。如果您需要不等同于这些indeces的特定数值,则需要enum来存放值,并使用switch语句来运行比较。

public enum MyEnum
        {
            Admin = 10,
            Manager = 20,
            Peon = 30
        }

public static int ConvertFromPosition(string pos)
{
       switch(pos.ToLower().Trim())
         {
           case "admin": return MyEnum.Admin; break;
           case "manager": return MyEnum.Manager; break;
           case "peon": return MyEnum.Peon; break;
           default:
                Throw new ApplicationException("Position " + pos + " is not a valid position.");
         }

}

请注意,比较字符串有更安全的方法,就像我说的那样,这只是快速和肮脏的。如果我们特定于文化,它会变得更加复杂。

答案 2 :(得分:0)

您的插入查询应该

“cmbRole.SelectedValue.ToString()”而不是“cmbRole.Text”。

SqlDataAdapter sda = new SqlDataAdapter("Insert into AccountRegistration(
Username, Password, RoleID, FullName, Address) VALUES 
('" + txtUsername.Text + "', '" + txtPassword.Text + "', '" + 
cmbRole.SelectedValue.ToString() + "', '" + txtFullName.Text +"', 
'"+txtAddress.Text+"')", con);

这可以解决您的问题。