我只希望复制用户表中的学生用户,并且在教师表中我只希望从用户表中复制教师用户。 如何为此问题格式化新循环。 谢谢。
以下是代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Web.UI;
using System.Data.OleDb;
using System.Web.UI.WebControls;
public partial class BulkUser : System.Web.UI.Page
{
DataTable Gendt = new DataTable();
DataTable Usersdt = new DataTable();
DataTable Studentsdt = new DataTable();
DataTable Facultydt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void UsersGridView_DataBinding(object sender, EventArgs e)
{
UsersGridView.DataSource = Gendt;
}
protected void StudentsGridView_DataBinding(object sender, EventArgs e)
{
StudentsGridView.DataSource = Studentsdt;
}
protected void FacultyGridView_DataBinding(object sender, EventArgs e)
{
FacultyGridView.DataSource = Facultydt;
}
protected void Button1_Click(object sender, EventArgs e)
{
OleDbConnection cnn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Server.MapPath(@"~\data\University.xlsx") + "; Extended Properties=Excel 12.0;");
OleDbCommand oconn = new OleDbCommand("select * from [Sheet1$]", cnn);
cnn.Open();
OleDbDataAdapter adp = new OleDbDataAdapter(oconn);
adp.Fill(Gendt);
cnn.Close();
Usersdt = Gendt.Copy();
Studentsdt = Gendt.Copy();
Studentsdt.Columns.Remove("UserType");
Facultydt = Studentsdt.Copy();
//foreach (DataRow dr in Usersdt.Rows)
//{
// foreach (DataRow dr1 in Studentsdt.Rows)
// {
// ////if (dr["UserType"].ToString().Contains("student"))
// // Studentsdt.ImportRow(Student);
// }
UsersGridView.DataBind();
StudentsGridView.DataBind();
FacultyGridView.DataBind();
}
}
答案 0 :(得分:0)
您可以按照此逻辑搜索UsersTable,并根据列值将整行(最后一列除外)复制到目标表。 此方法在遍历UsersTable时具有更好的性能。
foreach(DataRow dRow in Usersdt.Rows)
{
DataTable destinationTable = null;
if (dRow.Field<string>("UserType") == "student")
destinationTable = Studentsdt;
else if (dRow.Field<string>("UserType") == "Faculty")
destinationTable = Facultydt;
else
continue; // skip the current row
// copy the row skipping the last column as required
object[] rowData = new object[dRow.ItemArray.Length - 1];
Array.ConstrainedCopy(dRow.ItemArray, 0, rowData, 0, rowData.Length);
destinationTable.Rows.Add(rowData);
}
答案 1 :(得分:0)
假设您的数据位于Usersdt
,那么您需要将其过滤为
DataRow[] studentRows= Usersdt.Select("UserType=student");
DataRow[] facultyRows= Usersdt.Select("UserType=Faculty");
// import filtered rows in student and faculty tables one by one
foreach (DataRow row in studentRows)
{
Studentdt.ImportRow(row);
}
foreach (DataRow row in facultyRows)
{
Facultydt.ImportRow(row);
}