【发布时间】:2015-01-23 09:56:57
【问题描述】:
我的数据库中有 5 个数据,我想使用数据表在 gridView 中显示这些数据。但是我的代码只显示 GridView 中最后绑定的数据?我的代码是。请指出错误?
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString);
SqlCommand cmd = new SqlCommand("select Date from MusterRoll where EmpCode='"+code+"' and Month='1' and Year='2015'", conn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
var rows = ds.Tables[0].Rows;
foreach (DataRow row in rows)
{
string date1 = Convert.ToString(row["Date"]);
DateTime date2 = Convert.ToDateTime(date1);
SqlCommand cmd1 = new SqlCommand(" select TOP 1 m.EmpCode,m.NOH,m.OT,m.Late,m.Early,convert(varchar(10),m.Date,103)AS DATE,convert(varchar(10),s1.Shiftname,103)AS Shift From ShiftChange s,ShiftType s1,MusterRoll m WHERE s1.ShiftID=s.NShiftID and '" + date2 + "'>=Fromdate and Todate>='" + date2 + "' and m.Month = '1' and m.date='"+date2+"' and m.EmpCode='Neena' order by Todate desc", conn);
SqlDataAdapter sda1 = new SqlDataAdapter(cmd1);
DataTable dt = new DataTable();
sda1.Fill(dt);
//var rows1 = ds.Tables[0].Rows;
for (int rowIndex = 0; rowIndex < dt.Rows.Count; rowIndex++)
{
DataRow rpw = dt.Rows[rowIndex];
string EmpCode = rpw.Field<string>("EmpCode");
string NOH = rpw.Field<string>("NOH");
string OT = rpw.Field<string>("OT");
string Latae = rpw.Field<string>("Late");
string Early = rpw.Field<string>("Early");
string date3 =rpw.Field<string>("Date");
string Shift = rpw.Field<string>("Shift");
gvSingleemp.Visible = true;
gvSingleemp.DataSource = dt;
gvSingleemp.DataBind();
}
}
在我的 shiftChange 表中没有日期字段,而不是我有 fromDate 和 ToDate。我想根据 MusterRoll 表日期显示员工轮班。所以首先我选择了 MusteRoll date nd checkrd 这个日期存在于 ShiftChange FromDate 和 ToDate 之间(如果存在)显示 Shift
【问题讨论】:
-
顺便说一下,不要使用
dt.Rows[0].ItemArray[0].ToString(),而是使用rpw.Field<string>("EmpCode")。您的代码始终使用循环中的第一行而不是当前行。 -
我不明白你在做什么。您选择日期,然后循环它们以根据该日期从
EmpDetails中选择数据。但是你想在哪里显示这些记录?你想要多个网格视图吗?如果没有,为什么不通过EmpCode链接MusterRoll和EmpDetails?然后,您在一个查询中拥有所有数据,并且该表包含所有数据。 -
@Tim Schmelter,好的,你能指导我如何使用 foreach 循环和 DataTable 填充 GridView
-
我的意思是你不需要那些循环。我猜你想从
EmpDetails中选择所有记录,其中EmpCode是= code和MusterRoll.Month='1' and Year='2015'。那么你只需要一个sql查询来填充一个DataTable,它可以用作gvSingleemp的DataSource。对吗? -
你能写更多的代码吗?之后你如何使用rpw?当for循环关闭时?使用 sda 还是只是 sda1 ? ...为什么你实际上想要一个 for 循环?