在方法中,参数值可以赋值例如
public DataTable GetIndustryList(int industryID = 0)
{
}
代表没入传递参数时 附一个默认值
进入与数据库访问需要先
DataTable dtIndustry = ICustomer.Instance.GetIndustryList();
建立一个
二维表形式的数据对象
然后进入逻辑层
public DataTable GetIndustryList()
{
return dal.GetIndustryList();
}
然后再进入数据访问层
public DataTable GetIndustryList(int industryID = 0)
{
try
{
string sql = string.Format("select SI_ID,SI_IndustryName,SI_ParentID,SI_Createtime from Swt_IndustryManage");
if (industryID > 0)
sql += string.Format(" where SI_ID={0}", industryID);
//return DbHelperSQL.Query(sql).Tables[0];
return dbHelper.Query(sql).Tables[0];//Tables[0]表示通过Query返回得到后的第一张表
}
catch (Exception)
{
return null;
}
}
其中Query方法表示执行执行查询语句,返回DataSet,该方法是一个简单的数据库的公共基础方法,在进行类似功能时可以使用该方法
public DataSet Query(string SQLString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
DataSet ds = new DataSet();
try
{
connection.Open();
SqlDataAdapter command = new SqlDataAdapter(SQLString, connection);
command.Fill(ds, "ds");
}
catch (System.Data.SqlClient.SqlException ex)
{
throw new Exception(ex.Message);
}
return ds;
}
}
然后foreach循环遍历 ,相比for循环,foreach不需要判定其实位置,并且对于多维,代码不需要多少变化
dr["SI_IndustryName"]中的["SI_IndustryName"]为数据库中表的字段
foreach (DataRow dr in dtIndustry.Rows)
{
txtIndustryType.Items.Add(new ListItem(dr["SI_IndustryName"].ToString(), dr["SI_ID"].ToString()));
}