Sort datatable not working in C# ASP.NET? - c#

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();
}
}

Related

There is no row at position 2

I am trying to execute this code in getting an error as
There is no row at position 2"
How can I solve this?
public JsonResult Question()
{
try
{
string [] Question=new string[2];
SqlConnection con = new SqlConnection(connectionString: "Server = (localdb)\\mssqllocaldb; Database = QuestionDb; Trusted_Connection = True; MultipleActiveResultSets = true");
con.Open();
string query = "";
query += #"select Id,Sum(Yes) AS T_Yes,Sum(No) AS T_No,Sum(DontKnow) AS T_DontKnow from dbo.Questions Group By Id";
SqlCommand cmd = new SqlCommand(query, con);
cmd.CommandText = query;
DataTable dt = new DataTable();
SqlDataAdapter cmd1 = new SqlDataAdapter(cmd);
cmd1.Fill(dt);
if (dt.Rows.Count == 0)
{
Question[0] = "0";
Question[1] = "0";
Question[2] = "0";
}
else
{
Question[0] = dt.Rows[0]["T_Yes"].ToString();
Question[1] = dt.Rows[1]["T_No"].ToString();
Question[2] = dt.Rows[2]["T_DontKnow"].ToString();
}
return Json(Question);
The problem is that you are mixing rows and columns. Use:
Question[0] = dt.Rows[0]["T_Yes"].ToString();
Question[1] = dt.Rows[0]["T_No"].ToString();
Question[2] = dt.Rows[0]["T_DontKnow"].ToString();
You must use always dt.Rows[0] (instead of [1] or [2]) to get the properties of the first row.
You're checking only to row count = 0, try this:
Also for comentary answer you need all data for the pie chart so need to recover all records.
Add a reference to System.Data, System.Collections.Generic and System.Linq to your project if this does not compile
List<string[]> listofIdGroups;
List<string[]> listofIdGroups;
listofIdGroups = dt.Rows.OfType<DataRow>()
.Select(dr => new string[3] { dr["T_Yes"].ToString(), dr["T_No"].ToString(), dr["T_DontKnow"].ToString() }).ToList();
you can read the list this way:
foreach (string[] question in listofIdGroups)
{
Console.WriteLine("Yes:" + question[0] + Environment.NewLine + "No: " + question[1] + Environment.NewLine + "DontKnow: " + question[2]);
}
try it here:
https://dotnetfiddle.net/0S1N3c

Reading database data and forwarding to variables

Can anyone point me to where I make a mistake, I want to put a new sql query where I will read the data from the database and put them in my function, and in the end they will be displayed at the exit in the colon ("stunden") which currently appears on the first query SUM (zei.ZPZ_Std100) AS ZPZ_Std100
This looks like my entire code in the button
using (SqlConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["TestControl.Properties.Settings.DB"].ConnectionString))
{
boAPI4.Login login = new boAPI4.Login();
string cS = login.GetConnectionString();
DataAccess dA = new DataAccess(cS);
int userID = dA.getLpeID(login.GetBoUserNr());
PRAESENZZEIT q = new PRAESENZZEIT();
q.ZPZ_LPE_ID = userID;
if (db.State == ConnectionState.Closed)
db.Open();
string query = "SELECT per.LPE_Nr, zei.ZPZ_LPE_ID, zei.ZPZ_Datum, SUM (zei.ZPZ_Std100) AS ZPZ_Std100" +
" FROM DB.dbo.Z_PRAESENZZEIT zei INNER JOIN DB.dbo.A_PERSONAL per ON zei.ZPZ_LPE_ID = per.LPE_ID" +
$" WHERE zei.ZPZ_Datum BETWEEN '{dtFromDate.Value}' AND '{dtToDate.Value}' AND zei.ZPZ_LPE_ID='{userID.ToString()}' GROUP BY per.LPE_Nr, zei.ZPZ_LPE_ID, zei.ZPZ_Datum ORDER BY zei.ZPZ_Datum, per.LPE_Nr;";
pRAESENZZEITBindingSource.DataSource = db.Query<PRAESENZZEIT>(query, commandType: CommandType.Text);
List<PRAESENZZEIT> listid = new List<PRAESENZZEIT>();
PRAESENZZEIT pra = new PRAESENZZEIT();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TestControl.Properties.Settings.DB"].ConnectionString);
string sql = "SELECT ZPZ_Von,ZPZ_bis FROM DB.dbo.Z_PRAESENZZEIT WHERE ZPZ_LPE_ID='196'";
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
pra.ZPZ_Von = Convert.ToDateTime(dr["ZPZ_Von"]);
pra.ZPZ_Bis = Convert.ToDateTime(dr["ZPZ_bis"]);
listid.Add(pra);
}
dataGridView1.DataSource = listid;
con.Close();
DateTime kommen = DateTime.Now;
kommen = pra.ZPZ_Von;
if (pra.ZPZ_Von.TimeOfDay < new TimeSpan(8, 5, 0))
pra.ZPZ_Von = new DateTime(pra.ZPZ_Von.Year, pra.ZPZ_Von.Month, pra.ZPZ_Von.Day, 8, 0, 0);
DateTime gehen = DateTime.Now;
gehen = pra.ZPZ_Bis;
TimeSpan arbeitszeit = pra.ZPZ_Bis - pra.ZPZ_Von;
}
Currently, at the exit I get 0.
So, I need data that pass through the datetime variable
This is how it goes through the variables but returns the result as if it did not address base data, what's the problem? I understand if time [ZPZ_VON 07:45] that the exit should be 08:00..
SQL QUERY SELECT ZPZ_Von,ZPZ_bis FROM DB.dbo.Z_PRAESENZZEIT WHERE ZPZ_LPE_ID='196'
CODE:
List<PRAESENZZEIT> listid = new List<PRAESENZZEIT>();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TestControl.Properties.Settings.DB"].ConnectionString);
string sql = "SELECT ZPZ_Von, ZPZ_bis FROM DB.dbo.Z_PRAESENZZEIT WHERE ZPZ_LPE_ID='196'";
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
while (dr.Read())
{
PRAESENZZEIT pra = new PRAESENZZEIT();
pra.ZPZ_Von = Convert.ToDateTime(dr["ZPZ_Von"]);
pra.ZPZ_Bis = Convert.ToDateTime(dr["ZPZ_bis"]);
listid.Add(pra);
DateTime kommen = DateTime.Now;
kommen = pra.ZPZ_Von;
if (pra.ZPZ_Von.TimeOfDay < new TimeSpan(8, 5, 0))
pra.ZPZ_Von = new DateTime(pra.ZPZ_Von.Year, pra.ZPZ_Von.Month, pra.ZPZ_Von.Day, 8, 0, 0);
DateTime gehen = DateTime.Now;
gehen = pra.ZPZ_Bis;
TimeSpan arbeitszeit = pra.ZPZ_Bis - pra.ZPZ_Von;
}
con.Close();
DATABASE QUERY RESULT:
You were initializing the pra class outside the while loop. Which doesn't add new record in the list listid every time read DataRow from DataReader.
Try this below code:
using (SqlConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["TestControl.Properties.Settings.DB"].ConnectionString))
{
boAPI4.Login login = new boAPI4.Login();
string cS = login.GetConnectionString();
DataAccess dA = new DataAccess(cS);
int userID = dA.getLpeID(login.GetBoUserNr());
PRAESENZZEIT q = new PRAESENZZEIT();
q.ZPZ_LPE_ID = userID;
if (db.State == ConnectionState.Closed)
db.Open();
string query = "SELECT per.LPE_Nr, zei.ZPZ_LPE_ID, zei.ZPZ_Datum, SUM (zei.ZPZ_Std100) AS ZPZ_Std100" +
" FROM DB.dbo.Z_PRAESENZZEIT zei INNER JOIN DB.dbo.A_PERSONAL per ON zei.ZPZ_LPE_ID = per.LPE_ID" +
$" WHERE zei.ZPZ_Datum BETWEEN '{dtFromDate.Value}' AND '{dtToDate.Value}' AND zei.ZPZ_LPE_ID='{userID.ToString()}' GROUP BY per.LPE_Nr, zei.ZPZ_LPE_ID, zei.ZPZ_Datum ORDER BY zei.ZPZ_Datum, per.LPE_Nr;";
pRAESENZZEITBindingSource.DataSource = db.Query<PRAESENZZEIT>(query, commandType: CommandType.Text);
List<PRAESENZZEIT> listid = new List<PRAESENZZEIT>();
//PRAESENZZEIT pra = new PRAESENZZEIT(); //Needs to be inside the while loop.
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TestControl.Properties.Settings.DB"].ConnectionString);
string sql = "SELECT ZPZ_Von,ZPZ_bis FROM DB.dbo.Z_PRAESENZZEIT WHERE ZPZ_LPE_ID='196'";
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
var listid = ConvertDataTable<PRAESENZZEIT>(dt);
dataGridView1.DataSource = listid;
con.Close();
}
private static List<T> ConvertDataTable<T>(DataTable dt)
{
List<T> data = newList<T>();
foreach (DataRowrow in dt.Rows)
{
Titem = GetItem<T>(row);
data.Add(item);
}
return data;
}
private static TGetItem<T>(DataRow dr)
{
Type temp = typeof(T);
T obj =Activator.CreateInstance<T>();
foreach (DataColumncolumn in dr.Table.Columns)
{
foreach (PropertyInfopro in temp.GetProperties())
{
if (pro.Name == column.ColumnName)
pro.SetValue(obj,dr[column.ColumnName], null);
else
continue;
}
}
return obj;
}

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">

WPF C# There is no row at position 0

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
};
}

Categories