【前言】
上一篇博客介紹瞭如何使用DataGridView控件綁定數據源顯示數據。下面介紹另一種方法,不需要給DataGirdView控件綁定數據源,直接通過代碼將數據顯示到DataGirdView表格當中。
【界面設計】
用戶直接使用卡號登錄,在查詢上機記錄的時候也只能查詢自己的,不能查詢別人的,所有我直接用lable顯示當前用的登錄的卡號。
【代碼實現】
Factory層
public class LineInfoFactory
{
//獲取配置文件
string strDB = System.Configuration.ConfigurationManager.AppSettings["DB"];
public ILineInfo lineInfo()
{
string className = strDB + "." + "LineInfoDAL";
ILineInfo idal= (ILineInfo)Assembly.Load(strDB).CreateInstance(className);
return idal;
}
}
IDAL層
public interface ILineInfo
{
//查詢上機記錄
DataTable queryLineInfo(string cardNo);
}
DAL層
public class LineInfoDAL : ILineInfo
{
//實例化SqlHelper類
SqlHelper sqlHelper = new SqlHelper();
//查詢上機記錄
public DataTable queryLineInfo(string cardNo)
{
SqlParameter[] sqlParams =
{
new SqlParameter("@cardno",cardNo),
};
string sqlQuery = @"select cardno,ondatetime,offdatetime,consumetime,consumecash,status,computer from [Line_Info] where cardno=@cardNo and status='已下機'";
DataTable table = sqlHelper.ExecuteQuery(sqlQuery, sqlParams, CommandType.Text);
return table;
}
}
BLL層
public class LineInfoBLL
{
//查詢上機記錄
public DataTable queryLineInfo(string cardNo)
{
//實例化一個工廠層
LineInfoFactory lineFact = new LineInfoFactory();
//接收工廠層返回的接口
ILineInfo idal= lineFact.lineInfo();
DataTable table= idal.queryLineInfo(cardNo);
return table;
}
}
Facade層
public class LineInfoFacade
{
//查看上機記錄
public DataTable queryLineInfo(string cardNo)
{
//實例化B層
LineInfoBLL lineBll = new LineInfoBLL();
DataTable table= lineBll.queryLineInfo(cardNo);
return table;
}
}
UI層
private void btnQuery_Click(object sender, EventArgs e)
{
string cardNo = lblCardNo.Text.Trim();
//實例化外觀層
LineInfoFacade lineFac = new LineInfoFacade();
//接收外觀層傳過來的值
DataTable table = lineFac.queryLineInfo(cardNo);
int j = table.Rows.Count;
if (table.Rows.Count > 0)
{
//指定DataGridView控件的行數
dataGridView1.RowCount = j;
int i = 0;
while (i < j)
{
dataGridView1.Rows[i].Cells[0].Value = table.Rows[i][0];
dataGridView1.Rows[i].Cells[1].Value = table.Rows[i][1];
dataGridView1.Rows[i].Cells[2].Value = table.Rows[i][2];
dataGridView1.Rows[i].Cells[3].Value = table.Rows[i][3];
dataGridView1.Rows[i].Cells[4].Value = table.Rows[i][4];
dataGridView1.Rows[i].Cells[5].Value = table.Rows[i][5];
dataGridView1.Rows[i].Cells[6].Value = table.Rows[i][6];
i++;
}
}
else
{
MessageBox.Show("沒有查詢到上機記錄!");
}
}