如何在c#中从DataTable获取单元格或行值

时间:2015-11-01 09:40:32

标签: c#

我正在尝试从datatable获取 usert_id 值并将其分配给会话变量,但我无法在我的代码中获取user_id。我怎么能这样做?

try
        {
            conn.Open();
            MySqlCommand cmd = new MySqlCommand("Select * from students where user_name='" + loginname.Text + "' and user_password ='" + password.Text + "'", conn);
            MySqlDataAdapter da = new MySqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                ShowMessage(dt.Row['.user_id.']); //<-- Problem happens here
                Session["user_id"] = "bar";
                Response.Redirect("dashboard.aspx");
            }
            else
            {
                Response.Write("<script>alert('Please enter valid Username and Password')</script>");
            }
        }

1 个答案:

答案 0 :(得分:3)

.user_id。不是一个Row索引,我怀疑它是列名...你没有用圆点包围它吗?我认为它应该使用Row s 而不是Row和双引号:

ShowMessage(dt.Rows[0]["user_id"].ToString());