在C#中的Datatable数据变量的操作过程中,有时候我们需要知道DataTable中是否含有数据行或者DataTable的数据总行数,此时我们就可以先拿到DataTable中的Rows属性对象,通过Rows属性对象的Count属性即可获取总行数。
例如我们我们有个DataTable变量为dt,需要通过C#获取该DataTable的总行数可使用下列语句:
int rowCount = dt.Rows.Count;
一、C#获取该DataTable的总行数完整的源程序
protected void Page_Load(object sender, EventArgs e)
{
string conStr = "server=localhost;port=3306;user Id=root;password=331; database=timing ;Allow User Variables=True"; //连接字符串
MySqlConnection conn = null;
try
{
conn = new MySqlConnection(conStr);
conn.Open();
string sql1 = "select * from table1";
MySqlDataAdapter sda1 = new MySqlDataAdapter(sql1, conn);
DataTable dt = new DataTable();
//使用 SqlDataAdapter 对象 sda 将查询结果填充到 DataSet 对象 dt 中
sda1.Fill(dt);
int rowCount = dt.Rows.Count;
}
catch (Exception ex)
{
//MessageBox.Show("查询失败!" + ex.Message);
}
finally
{
if (conn != null)
{
//关闭数据库连接
conn.Close();
}
}
}
二、读取每条记录各个字段的值
int array11 = Convert.ToInt32(dt.Rows[0]["id"].ToString()); //读取第一条记录id字段的值
int array12 = Convert.ToInt32(dt.Rows[0]["ts"].ToString()); //读取第一条记录ts字段的值
int array21 = Convert.ToInt32(dt.Rows[1]["id"].ToString()); //读取第二条记录id字段的值
int array22 = Convert.ToInt32(dt.Rows[1]["ts"].ToString()); //读取第二条记录ts字段的值
读取每条记录各个字段的值完整的源程序
protected void Page_Load(object sender, EventArgs e)
{
string conStr = "server=localhost;port=3306;user Id=root;password=331; database=timing ;Allow User Variables=True"; //连接字符串
MySqlConnection conn = null;
try
{
conn = new MySqlConnection(conStr);
conn.Open();
string sql1 = "select * from table1";
MySqlDataAdapter sda1 = new MySqlDataAdapter(sql1, conn);
DataTable dt = new DataTable();
//使用 SqlDataAdapter 对象 sda 将查询结果填充到 DataSet 对象 dt 中
sda1.Fill(dt);
int rowCount = dt.Rows.Count;
int array11 = Convert.ToInt32(dt.Rows[0]["id"].ToString()); //读取第一条记录id字段的值
int array12 = Convert.ToInt32(dt.Rows[0]["ts"].ToString()); //读取第一条记录ts字段的值
int array21 = Convert.ToInt32(dt.Rows[1]["id"].ToString()); //读取第二条记录id字段的值
int array22 = Convert.ToInt32(dt.Rows[1]["ts"].ToString()); //读取第二条记录ts字段的值
}
catch (Exception ex)
{
//MessageBox.Show("查询失败!" + ex.Message);
}
finally
{
if (conn != null)
{
//关闭数据库连接
conn.Close();
}
}
}