简体   繁体   English

C#从充满SQL选择的数据表中读取值

[英]C# reading values from datatable filled with sql select

I am coding win form app, which checks on startup right of the currently logged user. 我正在编写win表单应用程序,它将检查当前登录用户的启动权限。 I had these right saved in MS SQL server in the table. 我将这些权利保存在表中的MS SQL Server中。 When importing data to Datatable, there is no problem. 将数据导入数据表时,没有问题。 But when I want to read value, there is message "cannot find column xy". 但是,当我想读取值时,出现消息“找不到列xy”。

SqlDataAdapter sdaRights = new SqlDataAdapter("SELECT * FROM rights WHERE [user]='" + System.Security.Principal.WindowsIdentity.GetCurrent().Name + "'", conn);

DataTable dtRights = new DataTable(); //this is creating a virtual table  
sdaRights.Fill(dtRights);
Object cellValue = dt.Rows[0][1];
int value = Convert.ToInt32(cellValue);
MessageBox.Show(value.ToString());

I would like, that program would save the value from SQL to int. 我想,该程序会将SQL中的值保存为int。

You are assuming that you have rows being returned, would be my first guess. 您假设您要返回行,这是我的第一个猜测。 You should loop through your DataTable instead of simply trying to access element 0 in it. 您应该遍历DataTable而不是简单地尝试访问其中的元素0。

DataTable dtRights = new DataTable();
sdaRights.Fill(dtRights);
foreach(DataRow row in dtRights.Rows) {
    Object cellValue = row[1];
    int value = Convert.ToInt32(cellValue);
    MessageBox.Show(value.ToString());
}
        using (SqlConnection con = new SqlConnection("your connection string"))
        {
            using (SqlCommand cmd = new SqlCommand("SELECT [column_you_want] FROM [rights] WHERE [user] = @user"))
            {
                cmd.Parameters.AddWithValue("@user", System.Security.Principal.WindowsIdentity.GetCurrent().Name);
                con.Open();

                int right = Convert.ToInt32(cmd.ExecuteScalar());
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM