WPF C# There is no row at position 0 - c#

I got trouble handling no row at position 0 any idea how can i fix this?
MY CODE:
public void FillAPModify()
{
sqliteConUserData.connection.Close();
sqliteConUserData.connection.Open();
var _command = sqliteConUserData.connection.CreateCommand();
var query = string.Format("SELECT * FROM tblTracking Where FileNumber = '" + StaticModel.clickNumValue + "' COLLATE NOCASE");
string commandText = query;
var _dataAdapter = new SQLiteDataAdapter(commandText, sqliteConUserData.connection);
DataSet _dataSet = new DataSet();
DataTable _dataTable = new DataTable();
_dataSet.Reset();
_dataAdapter.Fill(_dataSet);
_dataTable = _dataSet.Tables[0];
var rows = _dataTable.Rows;
string fileNumber = rows[0].ItemArray[0] as string; \\error
var shiftDate = rows[0].ItemArray[1];
var timeCreated = rows[0].ItemArray[2];
string remarks = rows[0].ItemArray[3] as string;
UserDataVar = new UserDataProperties
{
FileNumber = fileNumber,
ShiftDate = shiftDate.ToString(),
TimeCreated = timeCreated.ToString(),
Remarks = remarks
};
sqliteConUserData.connection.Close();
}
I tried this but no wokring:
if (_dataSet.Tables.Count > 0)
{
if (_dataSet.Tables[0].Rows.Count > 0)
{
\\my stuff
}
}

Your fix should work, but I always check to make sure the dataset isn't null as well and make it all one if statement.
if (_dataSet!= null && _dataSet.Tables.Count > 0 && dataSet.Tables[0].Rows.Count > 0)
{
_dataTable = _dataSet.Tables[0];
var rows = _dataTable.Rows;
string fileNumber = rows[0].ItemArray[0] as string; \\error
var shiftDate = rows[0].ItemArray[1];
var timeCreated = rows[0].ItemArray[2];
string remarks = rows[0].ItemArray[3] as string;
UserDataVar = new UserDataProperties
{
FileNumber = fileNumber,
ShiftDate = shiftDate.ToString(),
TimeCreated = timeCreated.ToString(),
Remarks = remarks
};
}

Related

Sort datatable not working in C# ASP.NET?

I am trying to apply sorting on datatable but it's working.I want to apply sorting by distance column.
Here is my output img
I want sort in ASC order ,from lowest to highest.
CODE:
SqlConnection cnn = new SqlConnection(connection);
string query = "SELECT PostCode,Latitude,Longitude FROM [kaykocou_admin].[kaykocou_admin].[Deals]";
SqlCommand cmd = new SqlCommand(query,cnn);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adp.Fill(dt);
DataTable dtnew = new DataTable();
DataRow _ravi;
if (dt.Rows.Count>0)
{
dtnew.Clear();
dtnew.Columns.Add("PostCode");
dtnew.Columns.Add("Lat");
dtnew.Columns.Add("Long");
// dtnew.Columns.Add("Lat 1");
// dtnew.Columns.Add("Long 1");
dtnew.Columns.Add("distance");
string str2 = GET("http://api.postcodes.io/postcodes/SW1A 0AA");
var serializer2 = new JavaScriptSerializer();
dynamic deserialize_post2 = serializer2.DeserializeObject(str2);
decimal Longitude1 = deserialize_post2["result"]["longitude"];
decimal Latitude1 = deserialize_post2["result"]["latitude"];
foreach (DataRow dr in dt.Rows)
{
string postcode = dr["PostCode"].ToString();
// string str1 = GET("http://api.postcodes.io/postcodes/" + postcode);
// string final = str1.Replace(#"{", "");
// string final2 = final.Replace(#"}", "");
// str1 = str1.Replace('[', ' ');
// str1 = str1.Replace(']', ' ');
// string result = "{ " + final2 + " }";
// var serializer = new JavaScriptSerializer();
// dynamic deserialize_post = serializer.DeserializeObject(str1);
decimal Longitude =Convert.ToDecimal( dr["Longitude"].ToString());
decimal Latitude =Convert.ToDecimal( dr["Latitude"].ToString()) ;
_ravi = dtnew.NewRow();
var sCoord = new GeoCoordinate(Convert.ToDouble(Latitude), Convert.ToDouble(Longitude));
var eCoord = new GeoCoordinate(Convert.ToDouble(Latitude1), Convert.ToDouble(Longitude1));
var distance=sCoord.GetDistanceTo(eCoord);
_ravi["PostCode"] = postcode;
_ravi["Lat"] = dr["Longitude"].ToString();
_ravi["Long"]= dr["Longitude"].ToString();
_ravi["distance"] =Convert.ToDouble( Math.Round(((distance / 1000.0) * 0.621371192), 2));
dtnew.Rows.Add(_ravi);
}
DataView view = dtnew.DefaultView;
view.Sort = "distance ASC";
DataTable sortedDate = view.ToTable();
//dtnew.DefaultView.Sort = "distance";
gr.DataSource = sortedDate;
gr.DataBind();
}
}

Importing data from excelsheet file into the mysql database C#

I have the following lines of code:
protected void btnUpload_Click(object sender, EventArgs e)
{
MySqlTransaction transaction;
string ex_id = "";
string file_name = Path.GetFileName(FileUpload1.FileName);
string Excel_path = Server.MapPath("~/Excel/" + file_name);
DataTable dtExceldata = new DataTable();//just added
FileUpload1.SaveAs(Excel_path);
OleDbConnection my_con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Excel_path + ";Extended Properties=Excel 8.0;Persist Security Info=False");
my_con.Open();
OleDbDataAdapter da = new OleDbDataAdapter("select * from [Sheet1$]", my_con);
da.Fill(dtExceldata);
if (dtExceldata.Rows.Count > 0)
{
//foreach (DataRow row in dtExceldata.Rows)
for (int i = 0; i <= dtExceldata.Rows.Count - 1; i++)
{
string ex_dir = dtExceldata.Rows[i]["website_a"].ToString();
//string ex_dir = row["website_a"].ToString();
string ex_email = dtExceldata.Rows[i]["email_id"].ToString();
// string ex_email = row["email_id"].ToString();
string ex_email1 = dtExceldata.Rows[i]["email_id2"].ToString();
//string ex_email1 = row["email_id2"].ToString();
string ex_email2 = dtExceldata.Rows[i]["email_id3"].ToString();
//string ex_email2 = row["email_id3"].ToString();
string ex_company = dtExceldata.Rows[i]["company"].ToString();
//string ex_company = row["company"].ToString();
string ex_contact = dtExceldata.Rows[i]["contact_name"].ToString();
//string ex_contact = row["contact_name"].ToString();
string ex_proposal = dtExceldata.Rows[i]["proposal_status"].ToString();
// string ex_proposal = row["proposal_status"].ToString();
string ex_reason = dtExceldata.Rows[i]["reason"].ToString();
//string ex_reason = row["reason"].ToString();
int chk = 0;
int type = 0;
int dup = 0;
int dir = 0;
if (ddlwebsites.SelectedIndex != 0)
{
dir = Convert.ToInt32(ddlwebsites.SelectedValue);
if (dir == 8)
{
type = 1;
}
}
foreach (ListItem lstAssign in ddlevents.Items)
{
if (lstAssign.Selected == true)
{
chk = 1;
}
}
if (type == 1 && chk == 0)
{
evyerror.Text = "Please Select the Event!!";
return;
}
else
{
string querycomp = "", compID = "";
querycomp = "Select * from barter_company where website like '%' '" + ex_dir + "' '%'";
string connStr = ConfigurationManager.ConnectionStrings["BarterConnectionString"].ToString();
connect = new MySqlConnection(connStr);
connect.Open();
transaction = connect.BeginTransaction();
try
{
ClassDtBaseConnect clsDtResult = new ClassDtBaseConnect();
DataTable dt = clsDtResult.GetDataTable(querycomp);
if (dt.Rows.Count > 0)
{
compID = dt.Rows[0]["comp_id"].ToString();
ViewState["comp_id"] = compID;
if (type == 1)
{
dup = checkforDuplicates(Convert.ToInt32(compID));
if (dup == 1)
{
//Confirm_MP.Show();
// ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "confirmation();", true);
}
}
//return;
}
else
{
string queryStr = "insert into barter_company (comp_name,website) values(?comp,?website)";
MySqlCommand cmd = new MySqlCommand(queryStr, connect, transaction);
cmd.Parameters.AddWithValue("?comp", ex_company);
cmd.Parameters.AddWithValue("?website", ex_dir);
cmd.ExecuteNonQuery();
cmd.CommandText = "Select LAST_INSERT_ID()";
compID = cmd.ExecuteScalar().ToString();
transaction.Commit();
connect.Close();
}
}
catch
{
transaction.Rollback();
}
if (dup == 0)
{
// create a connection string with your sql database
string connStr1 = ConfigurationManager.ConnectionStrings["BarterConnectionString"].ToString();
connect = new MySqlConnection(connStr1);
connect.Open();
DateTime date = new DateTime();
date = DateTime.ParseExact(txtsentdate.Text, "MM/dd/yyyy", null);
string SentDateString = date.ToString("yyyy/MM/dd");
//DateTime date = new DateTime();
//if (!string.IsNullOrEmpty(ex_date))
// {
//DateTime date = new DateTime();//added by chetan
//ex_date = ex_date.Split(' ')[0];//added by chetan
//date = DateTime.ParseExact(ex_date, "MM/dd/yyyy", null);//added by chetan
//string SentDateString = date.ToString("yyyy/MM/dd");//added by chetan
//DateTime SentDate = Convert.ToDateTime(SentDateString).Date;//added by chetan
//// DateTime date = DateTime.Parse(ex_date);//added by chetan
// }
//date = DateTime.ParseExact(ex_date, "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture);//added by chetan
//date = DateTime.ParseExact(ex_date, "MM/dd/yyyy", null);
// string SentDateString = date.ToString("yyyy/MM/dd");
transaction = connect.BeginTransaction();
try
{
string ex_uid = Session["session_barterUser_id"].ToString();
MySqlCommand cmd = new MySqlCommand("insert into barter_proposals(user_id, sent_date, website_a, email_id, email_id2, email_id3, company, contact_name, proposal_status, reason,type) values(?uid,?sentdate,?dir,?email,?email2,?email3,?comp,?cont_name,?pro_status,?reason,?type)", connect);
cmd.Parameters.AddWithValue("?uid", ex_uid);
cmd.Parameters.AddWithValue("?comp", compID);
cmd.Parameters.AddWithValue("?sentdate", SentDateString);
// command.Parameters.AddWithValue("?event", eventname);
cmd.Parameters.AddWithValue("?dir", dir);
// command.Parameters.AddWithValue("?bar_type", ddlbartertype.SelectedValue);
// command.Parameters.AddWithValue("?website_b", txtwebsite.Text);
//cmd.Parameters.AddWithValue("?comp", ex_company);
cmd.Parameters.AddWithValue("?cont_name", ex_contact);
cmd.Parameters.AddWithValue("?email", ex_email);
cmd.Parameters.AddWithValue("?email2", ex_email1);
cmd.Parameters.AddWithValue("?email3", ex_email2);
cmd.Parameters.AddWithValue("?pro_status", ex_proposal);
cmd.Parameters.AddWithValue("?reason", ex_reason);
cmd.Parameters.AddWithValue("?type", type);
// command.Parameters.AddWithValue("?type", type);
cmd.ExecuteNonQuery();
if (type == 1)
{
cmd.CommandText = "Select LAST_INSERT_ID()";
Int64 CurrentProId = Convert.ToInt64(cmd.ExecuteScalar());
int eventAssignID;
string QueryInqEventAssign = "insert into barter_propeventassign(prop_id,event_id) values(?pro_id,?event_id)";
foreach (ListItem lstAssign in ddlevents.Items)
{
if (lstAssign.Selected == true)
{
cmd = new MySqlCommand(QueryInqEventAssign, connect, transaction);
cmd.Parameters.AddWithValue("?pro_id", CurrentProId);
eventAssignID = Convert.ToInt32(lstAssign.Value);
cmd.Parameters.AddWithValue("?event_id", eventAssignID);
cmd.ExecuteNonQuery();
}
}
}//end of if
transaction.Commit();
connect.Close();
Response.Write("<script type=\"text/javascript\">alert('Proposal Added Successfully!!!');</script>");
}//end of try
catch (Exception ex)
{
transaction.Rollback();
Response.Write("<script>alert('There is an Error Ocurred:" + Server.HtmlEncode(ex.Message) + "')</script>");
}
finally
{
connect.Close();
}
}//ifdupzero
}//else
}//for//foreach
}//while //if
// dr.Close();//commented by chetan
my_con.Close();
if (System.IO.File.Exists(Excel_path))
{
System.IO.File.Delete(Excel_path);
}
}
suppose there are 2 entries in the excelsheet file.When trying to import,it is inserting those 2 rows entries into the database table.but the problem is that, the reader does not stop its execution.After reading 2 rows entry,it is reading 3rd row which is blank.i have used dr.close and it keeps on reading the rows entries which is blank.
Instead of checking if there are rows left (dr.Read()) as your loop condition, you could check if the first cell of the row is blank (dr[0].ToString() != String.Empty)
string file_name = Path.GetFileName(FileUpload1.FileName);
string Excel_path = Server.MapPath("~/Excel/" + file_name);
FileUpload1.SaveAs(Excel_path);
OleDbConnection my_con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Excel_path + ";Extended Properties=Excel 8.0;Persist Security Info=False");
my_con.Open();
OleDbCommand command = new OleDbCommand("select * from [Sheet1$]", my_con);
OleDbDataReader dr = command.ExecuteReader();
dr.Read();
while (dr[0].ToString() != String.Empty)
{
ex_id = dr[0].ToString();
string ex_uid = dr[1].ToString();
//get second row data and assign it ex_name variable
string ex_date = dr[2].ToString();
//get thirdt row data and assign it ex_name variable
string ex_dir = dr[3].ToString();
//get first row data and assign it ex_location variable
string ex_email = dr[4].ToString();
string ex_email1 = dr[5].ToString();
string ex_email2 = dr[6].ToString();
//string ex_company = dr[7].ToString();
string ex_company = dr[7].ToString();
string ex_contact = dr[8].ToString();
string ex_proposal = dr[9].ToString();
string ex_reason = dr[10].ToString();
...............
//Insert operation
...............
dr.Read();
}
dr.close();
my_con.close();
The premise of course is, that the first column is always filled if the rest of the row isn't blank.
If that isn't the case you can also check other columns in the loop condition.
there is various way of doing that
you can load excel data to datatable and then you can for loop for each row with perticular column name like this
string file_name = Path.GetFileName(FileUpload1.FileName);
string Excel_path = Server.MapPath("~/Excel/" + file_name);
DataTable dtExceldata = new DataTable();
FileUpload1.SaveAs(Excel_path);
OleDbConnection my_con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Excel_path + ";Extended
Properties=Excel 8.0;Persist Security Info=False");
OleDbDataAdapter da = new OleDbDataAdapter("select * from [Sheet1$]", my_con);
da.Fill(dtExceldata);
if(dtExceldata.Rows.Count>0)
{
for (int i = 0; i <= dtExceldata.Rows.Count - 1; i++)
{
//assign value to variable
//like below
//string ex_uid = dtExceldata.Rows[i]["columnName"];
//then insert operation here
}
}
see this excel file
and the datatable in c#
this loop will repeat for only number of row in datatable then also i practically tried this and it only loop for number of row (e.g two times) but i found a bug that if you will enter two row then five blank row then some data it will give you blank value in data table check your excel file there may some blank value as shown in attechment
then also you can skip blank value by checking null value in row like this
for (int i = 0; i <= dtExceldata.Rows.Count - 1; i++)
{
if (!String.IsNullOrEmpty(Convert.ToString(dtExceldata.Rows[i]["fieldvalues"])))
{
//assign value to variable
//like below
//string ex_uid = dtExceldata.Rows[i]["columnName"];
//then insert operation here
}
}

GridView - Line break inside Cell

I've been trying to get a line break between this inside every cell in column 1:
Value 1, Value 2,
Value 3
However the line breaks are just showing up as plain text in the cell:
<asp:GridView ID="dg1" runat="server" AllowSorting="true" OnSorting="Sort" AutoGenerateColumns="false" OnSelectedIndexChanged="dg1_SelectedIndexChanged" CssClass="DGgeneral" HeaderStyle-CssClass="DGheader" RowStyle-CssClass="DGrow1" AlternatingRowStyle-CssClass="DGrow2" >
<Columns>
</Columns>
</asp:GridView>
I am doing everything programatically so I can't add HTMLEncode="false" to BoundFields which is a huge pain.
public void SearchQuery(string sOrderBy, string sOrderByColumn)
{
//Create and Clear Datatable and Gridview
dt.Clear();
dg1.DataSource = null;
dg1.DataBind();
//Initialise Strings
string sTLTaskID = "";
string sTitle = "";
string sForename = "";
string sSurname = "";
string sEmail = "";
string sMobile = "";
string sHome = "";
string sDateTime = "";
string sState = "";
string sFormName = "";
//Initialise Column Names
dt.Columns.Add("Id/Form/State");
dt.Columns.Add("Title");
dt.Columns.Add("Forename");
dt.Columns.Add("Surname");
dt.Columns.Add("Email address");
dt.Columns.Add("Telephone 1");
dt.Columns.Add("Telephone 2");
dt.Columns.Add("Date & Time");
//Connect to ********
using (var connection = new SqlConnection(
"Data Source = ******;" +
"Integrated Security = ******;" +
"persist security info = ******;" +
"Initial Catalog = ********;"))
{
//Establish SQL Command
using (var command = connection.CreateCommand())
{
command.CommandText = "********";
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#TLTaskID", txtTLTaskID.Text);
command.Parameters.AddWithValue("#Name", txtName.Text);
command.Parameters.AddWithValue("#Email", txtEmail.Text);
command.Parameters.AddWithValue("#MNumber", txtNumber.Text);
command.Parameters.AddWithValue("#HNumber", txtNumber.Text);
if ((sOrderBy == null) || (sOrderBy == ""))
{
command.Parameters.AddWithValue("#AscDesc", "");
}
else if (sOrderBy == "Asc")
{
command.Parameters.AddWithValue("#AscDesc", "Asc");
}
else if (sOrderBy == "Desc")
{
command.Parameters.AddWithValue("#AscDesc", "Desc");
}
if ((sOrderByColumn == null) || (sOrderByColumn == ""))
{
command.Parameters.AddWithValue("#OrderByColumn", "");
}
else
{
command.Parameters.AddWithValue("#OrderByColumn", sOrderByColumn);
}
connection.Open();
//Initialise Column Names
using (var reader = command.ExecuteReader())
{
var column1 = reader.GetOrdinal("TLTaskID");
var column2 = reader.GetOrdinal("Title");
var column3 = reader.GetOrdinal("FirstName");
var column4 = reader.GetOrdinal("Surname");
var column5 = reader.GetOrdinal("Email");
var column6 = reader.GetOrdinal("Telephone1");
var column7 = reader.GetOrdinal("Telephone2");
var column8 = reader.GetOrdinal("DateTime");
var column9 = reader.GetOrdinal("State");
var column10 = reader.GetOrdinal("FormName");
//Loop until out of Rows in table
while (reader.Read())
{
//Set values of each row to a variable
var TLTaskID = reader.GetValue(column1);
var Title = reader.GetValue(column2);
var Forename = reader.GetValue(column3);
var Surname = reader.GetValue(column4);
var Email = reader.GetValue(column5);
var Mobile = reader.GetValue(column6);
var Home = reader.GetValue(column7);
var DateTime = reader.GetValue(column8);
var State = reader.GetValue(column9);
var FormName = reader.GetValue(column10);
//Convert to strings //Possible speed up ****
sTLTaskID = TLTaskID.ToString();
sTitle = Title.ToString();
sForename = Forename.ToString();
sSurname = Surname.ToString();
sEmail = Email.ToString();
sMobile = Mobile.ToString();
sHome = Home.ToString();
sDateTime = DateTime.ToString();
sState = State.ToString();
sFormName = FormName.ToString();
//Add to DataTable
var dr = dt.NewRow();
dr["Id/Form/State"] = sTLTaskID + ", " + sFormName + ", " + sState;
dr["Title"] = sTitle;
dr["Forename"] = sForename;
dr["Surname"] = sSurname;
dr["Email address"] = sEmail;
dr["Telephone 1"] = sMobile;
dr["Telephone 2"] = sHome;
dr["Date & Time"] = sDateTime;
dt.Rows.Add(dr);
//Set GridView's datasource to Datatable dr
dg1.DataSource = dt;
dg1.DataBind();
}
}
}
}
int iRowCount = dt.Rows.Count;
if (iRowCount > 0)
{
lblRecordTotal.Text = "Records: 1 - " + iRowCount.ToString() + " of " + iRowCount.ToString();
}
else
{
lblRecordTotal.Text = "No records found.";
}
}
If anything more is required please ask away.
Any ideas?
In your RowDataBound event of GridView add below line:
e.Row.Cells[0].Text = e.Row.Cells[0].Text.Replace("\n", "<br/>");
Note: You have to add OnRowDataBound event to GridView like this:
<asp:GridView ID="dg1" runat="server" OnRowDataBound="dg1_RowDataBound">

how to keep appending the list of values of a column until we get a new value in another column?

I am trying to keep appending a list of values to lookaheadRunInfo.gerrits until I get a new lookaheadRunInfo.ECJobLink in the while loop,I tried to create a variable “ECJoblink_previous” to capture the previous ECJoblink and create a new list only when they are different and keep appending until ECJoblink_previous changes,I tried as below but its not working,what am I missing?
try
{
Console.WriteLine("Connecting to MySQL...");
conn.Open();
string sql = #"some query";
var ECJoblink_previous ="";
MySqlCommand cmd = new MySqlCommand(sql, conn);
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
//Console.WriteLine(rdr[0] + " -- " + rdr[1]);
//Console.ReadLine();
lookaheadRunInfo.ECJobLink = rdr.GetString(0);
if (ECJoblink_previous == lookaheadRunInfo.ECJobLink)
{
//Keep appending the list of gerrits until we get a new lookaheadRunInfo.ECJobLink
var gerritList = new List<String>();
lookaheadRunInfo.gerrits = gerritList.Add(rdr.GetString(2));
}
ECJoblink_previous = lookaheadRunInfo.ECJobLink;
lookaheadRunInfo.UserSubmitted = rdr.GetString(2);
lookaheadRunInfo.SubmittedTime = rdr.GetString(3).ToString();
lookaheadRunInfo.RunStatus = "null";
lookaheadRunInfo.ElapsedTime = (DateTime.UtcNow - rdr.GetDateTime(3)).ToString();
lookaheadRunsInfo.Add(lookaheadRunInfo);
}
rdr.Close();
}
var lookaheadRunsInfo = new List<LookaheadRunInfo>();
LookAheadRunInfo lookaheadRunInfo;
var i = 0;
var ecJoblink_previous = string.Empty;
while (rdr.Read())
{
if (rdr.GetString(0) != ecJoblink_previous)
{
ecJoblink_previous = rdr.GetString(0);
if (i > 0)
{
lookaheadRunsInfo.Add(lookaheadRunInfo);
}
// Create a new lookaheadRunInfo
lookaheadRunInfo = new lookaheadRunInfo
{
ECJobLink = rdr.GetString(0),
UserSubmitted = rdr.GetString(2),
SubmittedTime = rdr.GetString(3).ToString(),
RunStatus = "null",
ElapsedTime = (DateTime.UtcNow - rdr.GetDateTime(3)).ToString(),
gerrits = new List<string>
{
rdr.GetString(2)
}
};
}
else
{
//Keep appending the list of gerrits until we get a new lookaheadRunInfo.ECJobLink
lookaheadRunInfo.gerrits.Add(rdr.GetString(2));
}
}

Generic list not being populated by db

I'm trying to populate a generic collection but having problems. I'm trying to populate myBookings, which is supposed to store a List. The methods below should fill myBookings with the correct List but for some reason when I count the result (int c), I'm getting a return of 0. Can anyone see what I'm doing wrong?
// .cs
public partial class _Default : System.Web.UI.Page
{
iClean.Bookings myBookings = new iClean.Bookings();
iClean.Booking myBooking = new iClean.Booking();
iClean.Controller myController = new iClean.Controller();
ListItem li = new ListItem();
protected void Page_Load(object sender, EventArgs e)
{
CurrentFname.Text = Profile.FirstName;
CurrentUname.Text = Profile.UserName;
CurrentLname.Text = Profile.LastName;
myBookings.AllBookings = this.GetBookings();
int c = myBookings.AllBookings.Count();
Name.Text = c.ToString();
Address.Text = myBooking.Address;
Phone.Text = myBooking.Phone;
Date.Text = myBooking.DueDate.ToString();
Comments.Text = myBooking.Comments;
}
public List<iClean.Booking> GetBookings()
{
List<iClean.Booking> bookings = new List<iClean.Booking>();
ArrayList records = this.Select("Bookings", "");
for (int i = 0; i < records.Count; i++)
{
iClean.Booking tempBooking = new iClean.Booking();
Hashtable row = (Hashtable)records[i];
tempBooking.ID = Convert.ToInt32(row["ID"]);
tempBooking.Name = Convert.ToString(row["ClientName"]);
tempBooking.Address = Convert.ToString(row["ClientAddress"]);
tempBooking.Phone = Convert.ToString(row["ClientPhone"]);
tempBooking.DueDate = Convert.ToDateTime(row["Bookingdate"]);
tempBooking.Completed = Convert.ToBoolean(row["Completed"]);
tempBooking.Paid = Convert.ToBoolean(row["Paid"]);
tempBooking.Cancelled = Convert.ToBoolean(row["Cancelled"]);
tempBooking.ReasonCancelled = Convert.ToString(row["ReasonCancelled"]);
tempBooking.ContractorPaid = Convert.ToBoolean(row["ContractorPaid"]);
tempBooking.Comments = Convert.ToString(row["Comments"]);
tempBooking.Windows = Convert.ToBoolean(row["Windows"]);
tempBooking.Gardening = Convert.ToBoolean(row["Gardening"]);
tempBooking.IndoorCleaning = Convert.ToBoolean(row["IndoorCleaning"]);
bookings.Add(tempBooking);
}
return bookings;
}
public ArrayList Select(string table, string conditions)
{
// Create something to hosue the records.
ArrayList records = new ArrayList();
try
{
// Open a connection.
OleDbConnection myConnection = new OleDbConnection(this.getConnectionString());
myConnection.Open();
// Generate the SQL
string sql = "SELECT * FROM " + table;
if (conditions != "") { sql += " WHERE " + conditions; }
// Console.WriteLine("Select SQL: " + sql); // In case we need to debug
// Run the SQL
OleDbCommand myCommand = new OleDbCommand(sql, myConnection);
OleDbDataReader myReader = myCommand.ExecuteReader();
// Go through the rows that were returned ...
while (myReader.Read())
{
// ... create Hashtable to keep the columns in, ...
Hashtable row = new Hashtable();
// ... add the fields ...
for (int i = 0; i < myReader.FieldCount; i++)
{
row.Add(myReader.GetName(i), myReader[i]);
}
// ... and store the row.
records.Add(row);
}
// Make sure to close the connection
myConnection.Close();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return records;
}
public string getConnectionString()
{
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=IQQuotes.accdb;";
return connectionString;
}
}
Just a guess, but try this:
public List<iClean.Booking> GetBookings()
{
List<iClean.Booking> bookings = new List<iClean.Booking>();
ArrayList records = this.Select("Bookings", "");
iClean.Booking tempBooking = new iClean.Booking();
for (int i = 0; i < records.Count; i++)
{
tempBooking = new iClean.Booking();
Hashtable row = (Hashtable)records[i];
tempBooking.ID = Convert.ToInt32(row["ID"]);
tempBooking.Name = Convert.ToString(row["ClientName"]);
tempBooking.Address = Convert.ToString(row["ClientAddress"]);
tempBooking.Phone = Convert.ToString(row["ClientPhone"]);
tempBooking.DueDate = Convert.ToDateTime(row["Bookingdate"]);
tempBooking.Completed = Convert.ToBoolean(row["Completed"]);
tempBooking.Paid = Convert.ToBoolean(row["Paid"]);
tempBooking.Cancelled = Convert.ToBoolean(row["Cancelled"]);
tempBooking.ReasonCancelled = Convert.ToString(row["ReasonCancelled"]);
tempBooking.ContractorPaid = Convert.ToBoolean(row["ContractorPaid"]);
tempBooking.Comments = Convert.ToString(row["Comments"]);
tempBooking.Windows = Convert.ToBoolean(row["Windows"]);
tempBooking.Gardening = Convert.ToBoolean(row["Gardening"]);
tempBooking.IndoorCleaning = Convert.ToBoolean(row["IndoorCleaning"]);
bookings.Add(tempBooking);
}
return bookings;
}

Categories