如何从数据集中获取值到一个变量?

问题描述:

请问while循环内有什么错误? c#.net Web应用程序.

Please what is an error within while loop? c#.net web application program.

protected void Page_Load(object sender, EventArgs e)
    {
        string path = "Data Source=192.168.1.14;Initial Catalog=nazer;User ID=sa;Password=admin*123";
        SqlConnection con = new SqlConnection(path);
        con.Open();
        string query = "select MAX(id) from tbl_samp1";
        SqlCommand cmd = new SqlCommand(query, con);        
        SqlDataReader dre=cmd.ExecuteReader();
        while (dre.Read())
        {            
            int values = (int)dre["id"];          //what error in this line? please...
        TextBox1.Text = values.ToString();
            
        }
        con.Close();
        
    }

使用
int values = int.Parse(dre["id"].ToString());    


1.当表中没有行时,查询结果可能为NULL
2.
1. The result of the query may be NULL when no rows in the table
2.
dre["id"]

-查询没有列名"id"
更改为

- the query does not have column name "id"
change to

select MAX(id) as id from tbl_samp1


尝试一下

Try This

int values = dre.GetInt32(id);