The below is my code to create account in my project. The code is working perfect till Response.Write(iduser) but the UPDATE command is not working. No error found using exception but MySQL's record is not updated.
try
{
string pet1 = "admin#testlite.php";
string MyConString = "DRIVER={MySQL ODBC 3.51 Driver};" + "SERVER=localhost;" + "DATABASE=newtest;" + "UID=root;" + "PASSWORD=**********;" + "OPTION=3";
OdbcConnection MyConnection = new OdbcConnection(MyConString);
OdbcCommand cmd = new OdbcCommand("Select id_user from awm_accounts where email=?", MyConnection);
cmd.Parameters.Add("#val1", OdbcType.VarChar, 255).Value = pet1;
MyConnection.Open();
OdbcDataReader dr = cmd.ExecuteReader();
if (dr.HasRows == false)
{
throw new Exception();
}
if (dr.Read())
{
int iduser = Convert.ToInt32(dr[0].ToString());
Account acct = new Account();
acct.Email = username.Text + domain.Text;
acct.MailIncomingLogin = username.Text + domain.Text;
acct.MailIncomingHost = "imap." + DropDownList1.SelectedValue;
acct.MailIncomingPassword = password.Text;
acct.MailIncomingPort = 993;
acct.MailOutgoingHost = "smtp." + DropDownList1.SelectedValue;
acct.MailOutgoingPort = 465;
acct.MailIncomingProtocol = IncomingMailProtocol.Imap4;
acct.MailOutgoingAuthentication = true;
acct.DefaultAccount = false;
acct.IDUser = 1;
integr.CreateUserFromAccount(acct);
Response.Write(iduser);
if (!IsPostBack)
{
cmd = new OdbcCommand("UPDATE awm_accounts SET id_user=? WHERE email=? ", MyConnection);
cmd.Parameters.Add("#tb_nickname", OdbcType.Int, 11).Value = iduser;
cmd.Parameters.Add("#tb_fullname", OdbcType.VarChar, 255).Value = username.Text + domain.Text;
cmd.ExecuteNonQuery();
}
}
MyConnection.Close();
}
catch (Exception exp)
{
Response.Write(exp);
}
I'm not sure about the Response.Write part but I am sure that you create a SQLCommand but never actually execute it.
Did you forget to put a cmd.executeNonScalar() in there?
Related
When I try to Export I got an Exception which says that the "Process cannot access the file "Mypath\Filename.xlsx" because it is being used by another process"
The Exception is Thrown when I try to Export and it is tracked back to the Line byte[] content = File.ReadAllBytes(fileName); So I don't Understand the Problem.
Am Not Using File stream to Read data
Here are the codes I Used
protected void BtnExport_Click(object sender, EventArgs e)
{
using (MydatabaseEntities dc = new MydatabaseEntities())
{
List<EmployeeMaster> emList = dc.EmployeeMasters.ToList();
StringBuilder sb = new StringBuilder();
if (emList.Count > 0)
{
string fileName = Path.Combine(Server.MapPath("~/ImportDocument"), DateTime.Now.ToString("ddMMyyyyhhmmss") + ".xlsx");
string conString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + fileName + "; Extended Properties='Excel 12.0;HDR=yes'";
using (OleDbConnection con = new OleDbConnection(conString))
{
string strCreateTab = "Create table EmployeeData(" +
"[Employee ID] varchar(50)," +
"[Company Name] varchar(200)," +
"[Contact Name] varchar(200)," +
"[Contact Title] varchar(200)," +
"[Employee Address] varchar(200)," +
"[Postal Code] varchar(50))";
if (con.State == ConnectionState.Closed)
{
con.Open();
}
OleDbCommand cmd = new OleDbCommand(strCreateTab, con);
cmd.ExecuteNonQuery();
string StrInsert = "Insert into EmployeeData([Employee ID],[Company Name]," + "[Contact Name],[Contact Title],[Employee Address], [Postal Code]" +
")values(?,?,?,?,?,?)";
OleDbCommand cmdIns = new OleDbCommand(StrInsert, con);
cmdIns.Parameters.Add("?", OleDbType.VarChar, 50);
cmdIns.Parameters.Add("?", OleDbType.VarChar, 200);
cmdIns.Parameters.Add("?", OleDbType.VarChar, 200);
cmdIns.Parameters.Add("?", OleDbType.VarChar, 200);
cmdIns.Parameters.Add("?", OleDbType.VarChar, 200);
cmdIns.Parameters.Add("?", OleDbType.VarChar, 50);
foreach (var i in emList)
{
cmdIns.Parameters[0].Value = i.EmployeeId;
cmdIns.Parameters[1].Value = i.CompanyName;
cmdIns.Parameters[2].Value = i.ContactName;
cmdIns.Parameters[3].Value = i.ContactTitle;
cmdIns.Parameters[4].Value = i.EmployeeAddress;
cmdIns.Parameters[5].Value = i.PostalCode;
cmdIns.ExecuteNonQuery();
}
//create Downloadable File
byte[] content = File.ReadAllBytes(fileName);
HttpContext context = HttpContext.Current;
context.Response.BinaryWrite(content);
context.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
context.Response.AppendHeader("Content-Disposition", "attachment; filename=EmployeeData.xlsx");
context.Response.End();
con.Close();
}
}
}
}
}
So Help me Please
I'm really Happy that I was Able to Fix my Problem with a simple trick I tried. The Error I was Getting that The file is Already Open, was caused by the connection I didn't close before creating a downloadable file!! Here is the change I made in Bold. :-)
protected void BtnExport_Click(object sender, EventArgs e)
{
using (MydatabaseEntities dc = new MydatabaseEntities())
{
List<EmployeeMaster> emList = dc.EmployeeMasters.ToList();
StringBuilder sb = new StringBuilder();
if (emList.Count > 0)
{
string fileName = Path.Combine(Server.MapPath("~/ImportDocument"), DateTime.Now.ToString("ddMMyyyyhhmmss") + ".xlsx");
string conString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + fileName + "; Extended Properties='Excel 12.0;HDR=yes'";
using (OleDbConnection con = new OleDbConnection(conString))
{
string strCreateTab = "Create table EmployeeData(" +
"[Employee ID] varchar(50)," +
"[Company Name] varchar(200)," +
"[Contact Name] varchar(200)," +
"[Contact Title] varchar(200)," +
"[Employee Address] varchar(200)," +
"[Postal Code] varchar(50))";
if (con.State == ConnectionState.Closed)
{
con.Open();
}
OleDbCommand cmd = new OleDbCommand(strCreateTab, con);
cmd.ExecuteNonQuery();
string StrInsert = "Insert into EmployeeData([Employee ID],[Company Name]," + "[Contact Name],[Contact Title],[Employee Address], [Postal Code]" +
")values(?,?,?,?,?,?)";
OleDbCommand cmdIns = new OleDbCommand(StrInsert, con);
cmdIns.Parameters.Add("?", OleDbType.VarChar, 50);
cmdIns.Parameters.Add("?", OleDbType.VarChar, 200);
cmdIns.Parameters.Add("?", OleDbType.VarChar, 200);
cmdIns.Parameters.Add("?", OleDbType.VarChar, 200);
cmdIns.Parameters.Add("?", OleDbType.VarChar, 200);
cmdIns.Parameters.Add("?", OleDbType.VarChar, 50);
foreach (var i in emList)
{
cmdIns.Parameters[0].Value = i.EmployeeId;
cmdIns.Parameters[1].Value = i.CompanyName;
cmdIns.Parameters[2].Value = i.ContactName;
cmdIns.Parameters[3].Value = i.ContactTitle;
cmdIns.Parameters[4].Value = i.EmployeeAddress;
cmdIns.Parameters[5].Value = i.PostalCode;
cmdIns.ExecuteNonQuery();
}
//create Downloadable File
**con.Close();**
byte[] content = File.ReadAllBytes(fileName);
HttpContext context = HttpContext.Current;
context.Response.BinaryWrite(content);
context.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
context.Response.AppendHeader("Content-Disposition", "attachment; filename=EmployeeData.xlsx");
context.Response.End();
}
}
}
}
}
I am working on asp.net project. I add one new page here and on that page i call multiple stored procedure. After executing this page for some time my site stops working and continue refreshing on browser without giving any error. After restarting the server it starts work again.
private void GetBiometrixData()
{
try
{
string data = string.Empty;
var length = ddlsession.Items.Count;
for (int i = 0; i < length; i++)
{
if (ddlsession.Items[i].Selected == true)
{
if (ddlsession.Items[i].Text != "--Select--")
{
data += ddlsession.Items[i].Text + ",";
}
}
}
data = data.Length > 0 ? data.Substring(0, data.Length - 1) : "";
data = data.Trim();
String strConnString = ConfigurationManager.ConnectionStrings["ak"].ConnectionString;
DateTime? FromDate = null;
DateTime? ToDate = null;
string session = "";
string TrainingType = "";
string EmployeeName = "";
string Course = "";
string Batch = "";
CultureInfo provider = CultureInfo.InvariantCulture;
string format = "MM/dd/yyyy";
if (string.IsNullOrEmpty(txtFromDate.Text.ToString()))
{
string TodayDate = DateTime.Now.ToString("MM/dd/yyyy");
FromDate = DateTime.ParseExact(TodayDate.ToString().Trim(), format, provider);
}
else
FromDate = DateTime.ParseExact(txtFromDate.Text.ToString().Trim(), format, provider);
if (string.IsNullOrEmpty(txtToDate.Text.ToString()))
ToDate = null;
else
ToDate = DateTime.ParseExact(txtToDate.Text.ToString().Trim(), format, provider);
if (ddlsession.SelectedItem.Text.ToString() == "--Select--")
session = null;
else
session = ddlsession.SelectedItem.Text.ToString();
if ((ddltrainingtype.SelectedItem.Text.ToString() == "--Select Training Type--"))
TrainingType = null;
else
TrainingType = ddltrainingtype.SelectedItem.Text.ToString();
if ((ddlCourse.SelectedItem.Text.ToString() == "--Select Course--"))
Course = null;
else
Course = ddlCourse.SelectedValue.ToString();
if ((ddlbatch.SelectedItem.Text.ToString() == "--Select Batch--"))
Batch = null;
else
Batch = ddlbatch.SelectedValue.ToString();
if (!string.IsNullOrEmpty(txtEmployeeName.Text.ToString()))
EmployeeName = txtEmployeeName.Text.ToString();
string strStatus = "";
if (Session["strStatus"] != null)
{
strStatus = Convert.ToString(Session["strStatus"]);
}
DataSet dsCount = new DataSet();
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand())
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
cmd.CommandTimeout = 0;
cmd.CommandText = "SP_GetBiometricAttendanceReport2";
cmd.Parameters.Add("#FromDate", System.Data.SqlDbType.DateTime).Value = FromDate;
cmd.Parameters.Add("#ToDate", System.Data.SqlDbType.DateTime).Value = ToDate;
cmd.Parameters.Add("#Session", SqlDbType.VarChar).Value = data;
cmd.Parameters.Add("#TrainingType", SqlDbType.VarChar).Value = TrainingType;
cmd.Parameters.Add("#Course", SqlDbType.VarChar).Value = Course;
cmd.Parameters.Add("#Batch", SqlDbType.VarChar).Value = Batch;
cmd.Parameters.Add("#EmployeeName", SqlDbType.VarChar).Value = EmployeeName;
cmd.Parameters.Add("#TotalStudents", SqlDbType.BigInt);
cmd.Parameters["#TotalStudents"].Direction = ParameterDirection.Output;
cmd.Parameters.Add("#TotalPresentStudents", SqlDbType.BigInt);
cmd.Parameters["#TotalPresentStudents"].Direction = ParameterDirection.Output;
cmd.Parameters.Add("#TotalAbsentStudents", SqlDbType.BigInt);
cmd.Parameters["#TotalAbsentStudents"].Direction = ParameterDirection.Output;
sda.SelectCommand = cmd;
sda.Fill(dsCount);
tblSummary.Visible = true;
lblTotalDrive.Text = cmd.Parameters["#TotalStudents"].Value.ToString();
lblTotalStudentAttended.Text = cmd.Parameters["#TotalPresentStudents"].Value.ToString();
lblTotalStudentAbsent.Text = cmd.Parameters["#TotalAbsentStudents"].Value.ToString();
}
}
}
DataSet ds = new DataSet();
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand())
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
if (!string.IsNullOrEmpty(Convert.ToString(FromDate)) && !string.IsNullOrEmpty(Convert.ToString(ToDate)))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
cmd.CommandTimeout = 0;
cmd.CommandText = "SP_GetBiometricAttendanceReportCount";
cmd.Parameters.Add("#FromDate", System.Data.SqlDbType.DateTime).Value = FromDate;
cmd.Parameters.Add("#ToDate", System.Data.SqlDbType.DateTime).Value = ToDate;
cmd.Parameters.Add("#Session", SqlDbType.VarChar).Value = data;
cmd.Parameters.Add("#TrainingType", SqlDbType.VarChar).Value = TrainingType;
cmd.Parameters.Add("#Course", SqlDbType.VarChar).Value = Course;
cmd.Parameters.Add("#Batch", SqlDbType.VarChar).Value = Batch;
cmd.Parameters.Add("#EmployeeName", SqlDbType.VarChar).Value = EmployeeName;
sda.SelectCommand = cmd;
sda.Fill(ds);
tblSummary.Visible = false;
GridView2.Visible = false;
RadGrid1.Visible = false;
GridView1.Visible = true;
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
//RadGrid1.DataSource = ds.Tables[0];
//RadGrid1.Rebind();
}
else
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
cmd.CommandTimeout = 0;
cmd.CommandText = "SP_GetBiometricAttendanceReport";
cmd.Parameters.Add("#FromDate", System.Data.SqlDbType.DateTime).Value = FromDate;
cmd.Parameters.Add("#ToDate", System.Data.SqlDbType.DateTime).Value = ToDate;
cmd.Parameters.Add("#Session", SqlDbType.VarChar).Value = session;
cmd.Parameters.Add("#TrainingType", SqlDbType.VarChar).Value = TrainingType;
cmd.Parameters.Add("#Course", SqlDbType.VarChar).Value = Course;
cmd.Parameters.Add("#EmployeeName", SqlDbType.VarChar).Value = EmployeeName;
cmd.Parameters.Add("#Status", SqlDbType.VarChar).Value = strStatus;
cmd.Parameters.Add("#Batch", SqlDbType.VarChar).Value = Batch;
sda.SelectCommand = cmd;
sda.Fill(ds);
GridView2.DataSource = ds.Tables[0];
GridView2.DataBind();
RadGrid1.DataSource = ds.Tables[0];
RadGrid1.Rebind();
if (strStatus == "")
lblResultStatus.Text = "<strong>Result of Total Students >></strong>";
else
lblResultStatus.Text = "<strong>Result of Total " + strStatus + " Students >></strong>";
}
}
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
//throw ex;
}
finally
{
con.Dispose();
con.Close();
}
}
Please help me to resolve this why site stops normal working and need to restart the server again and again.
Thanks...
I have a label in asp.net page and change its text in certain situations. Here is the code:
<asp:Label ID="errorMessage" runat="server" Text="Label" Visible="False"></asp:Label>
errorMessage.Text = MyGlobals.student.registerCourse(c, ref addList, course).ToString();
errorMessage.ForeColor = System.Drawing.Color.Red;
errorMessage.Visible = true;
When i debugged, i saw that MyGlobals.student.registerCourse(c, ref addList, course).ToString() method returns my error message well. Then i set the label visible, but when page loads i cannot see the label. Also, while debugging i saw that "textsetbyaddparsedsubobject" property of the label is false. Can that be the problem? Why is not the label being showed in my page? Can anyone help?
Thanks.
Edit: Here is the full code:
protected void bSubmitChanges_Click1(object sender, EventArgs e)
{
Userfunctions function = new Userfunctions();
List<string> dropList = new List<string>();
List<string> addList = new List<string>();
SqlConnection con = new SqlConnection();
con.ConnectionString = Userfunctions.GetConnectionString();
SqlCommand cmd;
con.Open();
string ID = MyGlobals.currentID;
try
{
for (int i = 1; i <= 6; i++)
{
string course;
if ((course = boxCRN(i)) != "")
{
cmd = new SqlCommand("select count (*) from CourseTable where CRN=#course", con);
cmd.Parameters.AddWithValue("#course", course);
int result = Convert.ToInt32(cmd.ExecuteScalar());
if (result > 0)
{
cmd = new SqlCommand("select * from CourseTable where CRN=#course", con);
cmd.Parameters.AddWithValue("#course", course);
cmd.ExecuteScalar();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
string query = "SELECT * FROM CourseTable WHERE CourseCode='" + dr["CourseCode"] + "' AND CourseNumber='" + dr["CourseNumber"] + "' AND Term='" + dr["Term"] + "'";
cmd = new SqlCommand(query, con);
SqlDataAdapter da2 = new SqlDataAdapter(cmd);
DataTable dt2 = new DataTable();
da2.Fill(dt2);
DataRow dr2 = dt2.Rows[0];
cmd = new SqlCommand("select * from PrereqTable where CourseCode='" + dr["CourseCode"] + "' AND CourseNumber='" + dr["CourseNumber"] + "' AND Term='" + dr["Term"] + "'", con);
da2 = new SqlDataAdapter(cmd);
dt2 = new DataTable();
da2.Fill(dt2);
List<string> pre = new List<string>();
foreach (DataRow dr5 in dt2.Rows)
{
pre.Add(Convert.ToString(dr5["pCourseCode"]) + Convert.ToString(dr5["pCourseNumber"]));
}
Course c = new Course(dr2["InstructorID"].ToString(), dr2["CourseCode"].ToString(), dr2["CourseNumber"].ToString(), dr2["CourseName"].ToString(), dr2["Term"].ToString(), dr2["CRN"].ToString(), dr2["Level"].ToString(), dr2["Credit"].ToString(), dr2["Description"].ToString(), dr2["Capacity"].ToString());
c.addPrereq(pre);
string message = MyGlobals.student.registerCourse(c, ref addList, course).ToString();
errorMessage.Text = message;
errorMessage.ForeColor = System.Drawing.Color.Red;
errorMessage.Visible = true;
Label1.Visible = true;
Label1.Text = "asdasdasd";
}
}
}
}
}
catch (Exception) { }
for (int i = 0; i < showCourses.Rows.Count; i++)
{
string a = ((DropDownList)showCourses.Rows[i].FindControl("actionmenu")).SelectedValue;
if (((DropDownList)showCourses.Rows[i].FindControl("actionmenu")).SelectedValue == "1")
{
string courseCode = showCourses.Rows[i].Cells[1].Text, courseNumber = showCourses.Rows[i].Cells[2].Text;
SqlCommand com = new SqlCommand("select * from CourseTable where CourseCode=#courseCode and CourseNumber=#courseNumber", con);
com.Parameters.AddWithValue("courseCode", courseCode);
com.Parameters.AddWithValue("courseNumber", courseNumber);
try
{
SqlDataAdapter da2 = new SqlDataAdapter(com);
DataTable dt2 = new DataTable();
da2.Fill(dt2);
DataRow dr2 = dt2.Rows[0];
Course c = new Course(dr2["InstructorID"].ToString(), dr2["CourseCode"].ToString(), dr2["CourseNumber"].ToString(), dr2["CourseName"].ToString(), dr2["Term"].ToString(), dr2["CRN"].ToString(), dr2["Level"].ToString(), dr2["Credit"].ToString(), dr2["Description"].ToString(), dr2["Capacity"].ToString());
Register reg = new Register(c, MyGlobals.student);
MyGlobals.student.dropCourse(reg);
dropList.Add(showCourses.Rows[i].Cells[1].Text + showCourses.Rows[i].Cells[2].Text);
}
catch (Exception) { }
}
}
foreach (string course in dropList)
{
for (int i = 0; i < MyGlobals.student.getRegistered().Count; i++ )
{
if (MyGlobals.student.getRegistered()[i].getCourse().getCode().ToString() + MyGlobals.student.getRegistered()[i].getCourse().getNumber().ToString() == course)
MyGlobals.student.dropCourse(MyGlobals.student.getRegistered()[i]);
}
cmd = new SqlCommand("delete from RegisterTable where StudentID='" + MyGlobals.currentID + "' and CourseCode='" + course.Substring(0, course.Length - 3) + "' and CourseNumber='" + course.Substring(course.Length - 3, 3) + "'", con);
cmd.ExecuteNonQuery();
}
try
{
foreach (string courses in addList)
{
string courseCode = "";
string courseNumber = "";
string term = MyGlobals.currentTerm + " " + MyGlobals.currentYear;
string q = ("select CourseCode from CourseTable where CRN=#courses");
string grade = "";
SqlCommand command = new SqlCommand(q, con);
command.Parameters.AddWithValue("#courses", courses);
courseCode = Convert.ToString(command.ExecuteScalar());
q = ("select CourseNumber from CourseTable where CRN=#courses");
command = new SqlCommand(q, con);
command.Parameters.AddWithValue("#courses", courses);
courseNumber = Convert.ToString(command.ExecuteScalar());
cmd = new SqlCommand("insert into RegisterTable (CourseCode,CourseNumber,Term,StudentID,Grade) values(#courseCode,#courseNumber,#term, #ID,'U')", con);
cmd.Parameters.AddWithValue("#courseCode", courseCode);
cmd.Parameters.AddWithValue("#courseNumber", courseNumber);
cmd.Parameters.AddWithValue("#term", term);
cmd.Parameters.AddWithValue("#ID", ID);
cmd.Parameters.AddWithValue("#grade", grade);
cmd.ExecuteNonQuery();
}
}
catch (Exception) { }
con.Close();
Response.Redirect("AddDropClasses.aspx");
}
}
And the registerCourse function:
public string registerCourse(Course course, ref List <string> addList, string crn) {
bool registered = true;
string message ="";
foreach (string s in course.getTime())
{
Userfunctions f = new Userfunctions();
foreach (Register r in this.register) {
if (r.getCourse().getTerm() == MyGlobals.currentTerm.ToString() + " " + MyGlobals.currentYear.ToString() && !f.TimeCheck(s, r.getCourse().getTime()))
{
registered = false;
message = "Time conflict";
}
}
}
if (registered) {
SqlConnection con = new SqlConnection();
con.ConnectionString = Userfunctions.GetConnectionString();
con.Open();
string id = MyGlobals.currentID;
SqlCommand cmd = new SqlCommand("SELECT count (*) from RegisterTable where CourseCode ='" + course.getCode() +"' and CourseNumber='" + course.getNumber() + "' and Term='" + course.getTerm()+"'" , con);
cmd.Parameters.AddWithValue("#id", id);
int active = Convert.ToInt32(cmd.ExecuteScalar());
if (active >= Convert.ToInt32(course.getCapacity())){
registered = false;
message = "Not enough capacity";
}
if (registered) {
foreach (string s in course.getPrerequisites()) {
if (!hasPassedCourse(s)) {
registered = false;
message = "Prerequisite error";
}
}
}
}
if (registered)
{
Register reg = new Register(course, MyGlobals.student);
MyGlobals.student.addToSchedule(reg);
addList.Add(crn);
}
return message;
}
Remove below line
Response.Redirect("AddDropClasses.aspx");
it will load your page again as new page
When you have Visible="false" set on the control then the control properties may not been instatiated fully.
I would try hiding the control using, errorMessage.Visible=false in the code-behind in your Page_Load instead.
I have developed an asp.net application in which input will be given through an excel sheet.
This application is working fine in a system with WINDOWS XP and MS office 2008.
If i try to run the same application in a system with WINDOWS 7 and MS office 2010 i am getting a Argument Null Exception.
Code:
foreach (var dr in data)
{
LHSupdate = new LHSUpdate();
if (!string.IsNullOrEmpty(Convert.ToString(dr["Associate Id"])))
{
AssociateID = Convert.ToString(dr["Associate Id"]);
}
LHSupdate.AssciateID = AssociateID;
if (!string.IsNullOrEmpty(Convert.ToString(dr["Associate Name"])))
{
AssociateName = Convert.ToString(dr["Associate Name"]);
}
LHSupdate.Name = AssociateName;
var designation = dsData.Tables["LHS"].AsEnumerable().Where(r => Convert.ToString(r["Associate Id"]).Trim() == LHSupdate.AssciateID.Trim());
if (designation != null)
{
foreach (var de in designation)
{
LHSupdate.Designation = Convert.ToString(de["Level"]);
}
}
else
{
LHSupdate.Designation = "";
}
LHSupdate.CourseName = Convert.ToString(dr["Trainings "]);
LHSupdate.CourseStatus = Convert.ToString(dr["Training Status"]);
LHSupdate.Score = Convert.ToString(dr["Credits"]);
LHSupdate.LearningMode = Convert.ToString(dr["Venue"]);
LHSupdate.StartDate = Convert.ToString(dr["Start Date"]);
LHSupdate.EndDate = Convert.ToString(dr["End Date"]);
lstLHS.Add(LHSupdate);
}
I am getting error in the line:
var designation = dsData.Tables["LHS"].AsEnumerable().Where(r => Convert.ToString(r["Associate Id"]).Trim() == LHSupdate.AssciateID.Trim());
Code:
private DataSet Getdata()
{
string connectionString = "";
string getExcelSheetName = string.Empty;
if (fuLHSEntry.HasFile)
{
string fileName = Path.GetFileName(fuLHSEntry.PostedFile.FileName);
string fileExtension = Path.GetExtension(fuLHSEntry.PostedFile.FileName);
string fileLocation = Server.MapPath("~/App_Data/" + fileName);
fuLHSEntry.SaveAs(fileLocation);
if (fileExtension == ".xls")
{
connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileLocation + #";Extended Properties=" + Convert.ToChar(34).ToString() + #"Excel 8.0;Imex=1;HDR=Yes;" + Convert.ToChar(34).ToString();
}
else if (fileExtension == ".xlsx" || fileExtension == ".xlsm")
{
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileLocation + #";Extended Properties=" + Convert.ToChar(34).ToString() + #"Excel 12.0;IMEX=2;HDR=Yes;" + Convert.ToChar(34).ToString();
}
OleDbConnection con = new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
OleDbDataAdapter dAdapter = new OleDbDataAdapter(cmd);
DataTable dtExcelRecords = new DataTable();
con.Open();
DataTable dtExcelSheetName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
int count = 0;
foreach (DataRow dr in dtExcelSheetName.Rows)
{
getExcelSheetName = GetSheetName(dr);
if (!string.IsNullOrEmpty(getExcelSheetName))
{
cmd.CommandText = "SELECT * FROM [" + getExcelSheetName + "]";
dAdapter.SelectCommand = cmd;
if (getExcelSheetName.ToUpper().Contains("LEARNING"))
{
getExcelSheetName = "LEARNING";
}
else
{
getExcelSheetName = "LHS";
}
dAdapter.Fill(dsData, getExcelSheetName);
count++;
if (count == 2)
{
break;
}
}
}
con.Close();
}
return dsData;
}
Please help me in resolving this issue.
Thanks,
Raji
From your code it appears that the table can have two possible names.
Either give it always the same name that you're using later when reading:
dAdapter.Fill(dsData, "LHS");
Or you can take the table by index ignoring its name altogether:
var designation = dsData.Tables[0].AsEnumerable().Where(r => Convert.ToString(r["Associate Id"]).Trim() == LHSupdate.AssciateID.Trim());
The following code works fine when the limit is 0,1 when I limit them to 0,30 I cannot retrieve records I am sure that my database has enough number of records.
But I doubt the syntax after dr[3].ToString(); How to retrieve all of them.
string MyConString = "DRIVER={MySQL ODBC 3.51 Driver};" + "SERVER=localhost;" + "DATABASE=malla_softmail2;" + "UID=xxx;" + "PASSWORD=xxx;" + "OPTION=3";
OdbcConnection MyConnection = new OdbcConnection(MyConString);
MyConnection.Open();
OdbcCommand cmd = new OdbcCommand("Select * from awm_test where user=? limit= 0, 1", MyConnection);
cmd.Parameters.Add("#email", OdbcType.VarChar, 255).Value = "hello";
OdbcDataReader dr = cmd.ExecuteReader();
if (dr.HasRows == false)
{
// throw new Exception();
}
if (dr.Read())
{
string a = dr[0].ToString();
string b = dr[1].ToString();
string c = dr[2].ToString();
//string d = dr[3].ToString();
//string f = dr[4].ToString();
//string g = dr[5].ToString();
Response.Write(a);
Response.Write(b);
Response.Write(c);
//Response.Write(d);
//Response.Write(f);
//Response.Write(g);
You're only processing the first record returned by your query. Try:
while (dr.Read()) {
string firstField = dr[0].ToString();
string secondField = dr[1].ToString();
string thirdField = dr[2].ToString();
// ...
}
You just need to read the rows in a loop with while(dr.Read()) {...do stuff for each row...} - each dr.Read() moves to the next row.