how to make line break between words in this following code ? i want to show each output have line break like this so that it can be seen properly. this is my code and output that i want :
try
{
//DataTable dtTemp = (DataTable)ViewState["Information"];
DataTable dtDistinctRecords = dtTemp.DefaultView.ToTable(true, "prod_line");
DataTable dtStudentName = dtTemp.DefaultView.ToTable(true, "request_date");
DataTable a = new DataTable();
DataTable dtStudent = new DataTable();
dtStudent.Columns.Add("request_date");
foreach (DataRow rows in dtDistinctRecords.Rows)
{
dtStudent.Columns.Add(rows["prod_line"].ToString());
}
foreach (DataRow row in dtStudentName.Rows)
{
DataRow dr = dtStudent.NewRow();
dr["request_date"] = row["request_date"];
DataView dv = new DataView(dtTemp);
dv.RowFilter = "request_date='" + row["request_date"] + "'";
DataTable dtStudentdtl = dv.ToTable();
for (int i = 0; i < dtStudentdtl.Rows.Count; i++)
{
string colValue = dtStudentdtl.Rows[i]["jo_no"].ToString();
string colValue2 = dtStudentdtl.Rows[i]["qty"].ToString();
string colValue3 = dtStudentdtl.Rows[i]["need_by_date"].ToString();
string colValue4 = dtStudentdtl.Rows[i]["process_id"].ToString();
dr[dtStudentdtl.Rows[i]["prod_line"].ToString()] = "Job Order: " + colValue + " Quantity: " + colValue2 + " Need by Date: " + colValue3 + " Status: " + colValue4;
var joinedWords = string.Join(" ", dtStudent);
}
dtStudent.Rows.InsertAt(dr, dtStudent.Rows.Count);
}
GridView1.CellPadding = 10;
GridView1.DataSource = dtStudent;
GridView1.DataBind();
GridView_Row_Merger(GridView1);
con.Close();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
link output that i want
Here's the first result from google for you, adding line break,
or for short \r\n
I made some changes in your for loop to make a sample code snippet:
string colValue = "job order: 124"+System.Environment.NewLine+System.Environment.NewLine;
string colValue2 = "Quantity: 100" + System.Environment.NewLine + System.Environment.NewLine;
string colValue3 = "Need by Date:2/5/2017" + System.Environment.NewLine + System.Environment.NewLine;
string colValue4 = "Status: Pending"+System.Environment.NewLine;
string finalString = colValue + colValue2 + colValue3 + colValue4;
and in front end i am getting following output:
Hope it will work for you.
Related
So, here it is my problem
I have four dropdowns in the screen, and all four are loaded when the screen loads, also when I change the first combobox, all three load with the selectedindex method, no problems in that.
But when I manually clear the first combobox, the remaining three retain the same values as before and I am not able to reset them. Any suggestions ?
private void comboBox_commodity_SelectedIndexChanged(object sender, EventArgs e)
{
//filter stat type
if (!comboBox_commodity.Text.Equals(""))
{
statTypes = new List<string>();
foreach (string groupID in groupIds)
{
string sql = "select [ERSStatisticType_Attribute] from " + schemaName + "ERSStatisticType_LU " +
"WHERE ERSStatisticType_ID IN (SELECT DISTINCT[ERSCommodity_ERSStatisticType_ID] FROM "
+ schemaName + "[ERSCommodityDataSeries] WHERE [ERSCommodity_ERSGroup_ID] = " + groupID
+ " and ERSCommoditySubCommodity_ID = " + getCommodityID(comboBox_commodity.Text) + " ) ";
DataTable dt = GetData(sql);
DataRow[] dr = dt.Select();
foreach (DataRow row in dr)
{
statTypes.Add(row["ERSStatisticType_Attribute"].ToString());
}
}
comboBox_statType.DataSource = statTypes;
comboBox_statType.SelectedItem = null;
//filter unit
//filter source
source = new List<string>();
foreach (string groupID in groupIds)
{
string sql = "select DISTINCT ERSSource_Desc from " + schemaName
+ "ERSSource_LU where ERSSource_ID IN (SELECT DISTINCT[ERSCommodity_ERSSource_ID] FROM " + schemaName + "[ERSCommodityDataSeries] WHERE [ERSCommodity_ERSGroup_ID] = " + groupID +
" and ERSCommoditySubCommodity_ID = " + getCommodityID(comboBox_commodity.Text) + " ) ORDER BY ERSSource_Desc";
DataTable dt = GetData(sql);
DataRow[] dr = dt.Select();
foreach (DataRow row in dr)
{
source.Add(row["ERSSource_Desc"].ToString());
}
}
comboBox_source.DataSource = source;
comboBox_source.SelectedItem = null;
unit = new List<string>();
foreach (string groupID in groupIds)
{
string sql = "select distinct ERSUnit_Desc from " + schemaName
+ "ERSUnit_LU ulu" + "," + schemaName + "ERSCommodityDataSeries cds" + "," + schemaName + "ERSDataValues dv " +
" where ulu.ERSUnit_ID=dv.ERSDataValues_ERSUnit_ID " +
" and cds.ERSCommoditySubCommodity_ID= " + getCommodityID(comboBox_commodity.Text) +
" and cds.ERSCommodity_ID=dv.ERSDataValues_ERSCommodity_ID " +
" and [ERSCommodity_ERSGroup_ID] = " + groupID;
DataTable dt = GetData(sql);
DataRow[] dr = dt.Select();
foreach (DataRow row in dr)
{
unit.Add(row["ERSUnit_Desc"].ToString());
}
}
comboBox1_unit.DataSource = unit;
comboBox1_unit.SelectedItem = null;
}
else
{
fillCommodityCombobox();
fillSourceCombobox();
fillUnitCombobox();
fillStatTypeCombobox();
}
}
If I manually clear the combobox, all other three values should be loaded with all the revelant values.
Now, I'm not 100% on your utilization here, but based off the initial issue I would use the Textupdate Event Handler like this:
private void comboBox1_TextUpdate(object sender, EventArgs e)
{
ClearCmboboxesOnFirstEmpty(comboBox_commodity.Text);
}
private void ClearCmboboxesOnFirstEmpty(string comboValue)
{
if(comboValue == "")
{
fillCommodityCombobox();
fillSourceCombobox();
fillUnitCombobox();
fillStatTypeCombobox();
}
}
I'm trying to export the results of a stored procedure to Excel and receiving the following error when running: System.Data.OleDb.OleDbException (0x80040E14): Syntax error (missing operator) in query expression. Below is the code I am using. The excel file gets created but there is no data populating the file.
string TableColumns = "";
// Get the Column List from Data Table so can create Excel Sheet with Header
foreach (DataTable table in ds.Tables)
{
foreach (DataColumn column in table.Columns)
{
TableColumns += column + "],[";
}
}
// Replace most right comma from Columnlist
TableColumns = ("[" + TableColumns.Replace(",", " Text,").TrimEnd(','));
TableColumns = TableColumns.Remove(TableColumns.Length - 2);
//Use OLE DB Connection and Create Excel Sheet
Excel_OLE_Con.ConnectionString = connstring;
Excel_OLE_Con.Open();
Excel_OLE_Cmd.Connection = Excel_OLE_Con;
Excel_OLE_Cmd.CommandText = "Create table " + SheetName + " (" + TableColumns + ")";
Excel_OLE_Cmd.ExecuteNonQuery();
//Write Data to Excel Sheet from DataTable dynamically
foreach (DataTable table in ds.Tables)
{
String sqlCommandInsert = "";
String sqlCommandValue = "";
foreach (DataColumn dataColumn in table.Columns)
{
sqlCommandValue += dataColumn + "],[";
}
sqlCommandValue = "[" + sqlCommandValue.TrimEnd(',');
sqlCommandValue = sqlCommandValue.Remove(sqlCommandValue.Length - 2);
sqlCommandInsert = "INSERT into " + SheetName + "(" + sqlCommandValue + ") VALUES(";
int columnCount = table.Columns.Count;
foreach (DataRow row in table.Rows)
{
string columnvalues = "";
for (int i = 0; i < columnCount; i++)
{
int index = table.Rows.IndexOf(row);
columnvalues += "'" + table.Rows[index].ItemArray[i] + "',";
}
columnvalues = columnvalues.TrimEnd(',');
var command = sqlCommandInsert + columnvalues + ")";
Excel_OLE_Cmd.CommandText = command;
Excel_OLE_Cmd.ExecuteNonQuery();
}
}
Excel_OLE_Con.Close();
Dts.TaskResult = (int)ScriptResults.Success;
So the issue is related to you have an unescaped single quote in your data. Two options for dealing with that are to escape the single quote (turn it into two single quotes):
string myData = "This string won't work";
string myDataEscaped = myData.Replace("'", "''");
or the other option (and more robust) is to use a parameterized query. I will use just the lower part of your code where you are doing this query build up and insertion and show you how that can be done (along with some cleanup and making use of StringBuilder). Note I did not compile and test this as I don't have any test data to use.
var tableColumns = string.Join(",", columns.Cast<DataColumn>().Select(x => "[" + x.ColumnName + "]"));
var insertBase = $"INSERT into {SheetName} ({tableColumns}) VALUES(";
int columnCount = table.Columns.Count;
foreach (DataRow row in table.Rows)
{
Excel_OLE_Cmd.Parameters.Clear(); // Since you are reusing the command you have to clear the parameters
var command = new StringBuilder(insertBase);
var index = table.Rows.IndexOf(row);
// I will assume you always have at least one column, otherwise these lines would fail
// Add the first row before the loop that way we don't have to delete the end comma
var param = $"#param_{index}_0";
command.Append(param);
Excel_OLE_Cmd.Parameters.AddWithValue(param, table.Rows[index].ItemArray[0]);
for (int i = 1; i < columnCount; ++i)
{
param = $"#param_{index}_{i}"
command.Append("," + param);
Excel_OLE_Cmd.Parameters.AddWithValue(param, table.Rows[index].ItemArray[i]);
}
command.Append(")");
Excel_OLE_Cmd.CommandText = command.ToString();
Excel_OLE_Cmd.ExecuteNonQuery();
}
I want to make sums of columns and rows in a gridview , I tried so many ways and I can't do it. I'm trying to understand what's wrong. I'm sorry If my code is a mess. I'm using ASP.NET C#. For now it is enough to show sum only in a response.write, later i'll put it on a column/row.
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=*****;Initial Catalog=***;User=***;password=**");
//query para o select das especialidades todas
string specstring = "SELECT Speciality.Shortname, SUM(1) as contar " +
"FROM DoctorEnterpriseDetails INNER JOIN " +
"Speciality ON DoctorEnterpriseDetails.Speciality1 = Speciality.SpecialityId INNER JOIN " +
" GroupType ON DoctorEnterpriseDetails.GroupId = GroupType.GroupId " +
" WHERE (DoctorEnterpriseDetails.EnterpriseId = 48) " +
" GROUP BY Speciality.Shortname ";
SqlCommand command = new SqlCommand(specstring, conn);
command.Connection.Open();
SqlDataAdapter myDataAdapter = new SqlDataAdapter();
myDataAdapter.SelectCommand = command;
DataTable specstringtable = new DataTable();
myDataAdapter.Fill(specstringtable);
specstring = "";
for (int i = 0; i < specstringtable.Rows.Count; i++)
{
if (specstring == "")
{
specstring = "[" + specstringtable.Rows[i][0] + "]".ToString();
}
else
{
specstring = specstring + ", " + "[" + specstringtable.Rows[i][0] + "]";
}
}
command.Connection.Close();
////query para a pivot table
string querystring = "SELECT Description AS Categoria, " + specstring +
"FROM (SELECT GroupType.Description, Speciality.Shortname, SUM(1) AS contar, GroupType.GroupId " +
"FROM DoctorEnterpriseDetails INNER JOIN " +
"Speciality ON DoctorEnterpriseDetails.Speciality1 = Speciality.SpecialityId INNER JOIN " +
"GroupType ON DoctorEnterpriseDetails.GroupId = GroupType.GroupId " +
"WHERE (DoctorEnterpriseDetails.EnterpriseId = 48) " +
"GROUP BY GroupType.Description, Speciality.Shortname, DoctorEnterpriseDetails.GroupId, GroupType.GroupId) as ps " +
"PIVOT (SUM(contar) FOR Shortname IN (" + specstring + ")) pvt " +
"ORDER BY GroupId; ";
////Response.Write(querystring);
SqlCommand command2 = new SqlCommand(querystring, conn);
command2.Connection.Open();
SqlDataAdapter myDataAdapter2 = new SqlDataAdapter();
myDataAdapter2.SelectCommand = command2;
DataTable cobtable = new DataTable();
myDataAdapter2.Fill(cobtable);
DataColumn cl = cobtable.Columns.Add("Total");
cobtable.Columns["Total"].SetOrdinal(1);
DataRow dr;
dr = cobtable.NewRow();
dr["Categoria"] = "Total";
cobtable.Rows.InsertAt(dr, 0);
dr = cobtable.NewRow();
dr["Categoria"] = "";
cobtable.Rows.InsertAt(dr, 1);
dr = cobtable.NewRow();
dr["Categoria"] = "%";
cobtable.Rows.InsertAt(dr, 3);
dr = cobtable.NewRow();
dr["Categoria"] = "";
cobtable.Rows.InsertAt(dr, 4);
dr = cobtable.NewRow();
dr["Categoria"] = "%";
cobtable.Rows.InsertAt(dr, 6);
dr = cobtable.NewRow();
dr["Categoria"] = "";
cobtable.Rows.InsertAt(dr, 7);
dr = cobtable.NewRow();
dr["Categoria"] = "%";
cobtable.Rows.InsertAt(dr, 9);
GroupGrid.DataSource = cobtable;
GroupGrid.DataBind();
//GroupGrid.FooterRow.Cells[1].Text = cobtable.Compute("sum(" + cobtable.Columns[3].ColumnName + ")", null).ToString();
decimal a = 0, soma = 0;
string la = "";
//Response.Write(GroupGrid.Rows[0].Cells.Count);
for (int i = 3; i <= (GroupGrid.Rows[0].Cells.Count); i++)
{
Response.Write("!");
//string l3 = GroupGrid.Rows[6].Cells[i-1].Text;
// Response.Write(l3);
Response.Write(GroupGrid.Rows[5].Cells[i - 1].Text);
// la = GroupGrid.Rows[5].Cells[i - 1].Text;
// sum += Convert.ToInt32(la);
//sum = Convert.ToInt32(GroupGrid.Rows[5].Cells[i - 1].Text.ToString());
//a = a + sum;
//GroupGrid.FooterRow.Cells[1].Text = sum.ToString();
}
// Response.Write(a.ToString());
You are right your code is a little mess ;)
I tried to understand what you mean so just for a case here you have the example how to sum the values in row, sum the values in column or some both columns and rows so sum of all cells.
These examples assume you are not having cells spaning through more then one row or column and that the total sum of your values is less then "long" size and each cell contains number that is "integer".
public void DisplayGridViewSums(GridView gv)
{
foreach (GridViewRow row in gv.Rows)
{
long sum = SumValuesInRow(row);
Console.WriteLine("Sum of values in raw '{0}' is: {1}", row.RowIndex, sum);
}
for (int i=0; i<gv.Columns.Count;i++)
{
long sum = SumValuesInColumn(gv,i);
Console.WriteLine("Sum of values in column '{0}' with header '{1}' is: {2}",i, gv.Columns[i].HeaderText, sum);
}
long totalsum = SumColumnsAndRowsInGridView(gv);
Console.WriteLine("Sum of all cells in each row is: {0}", totalsum);
}
public long SumColumnsAndRowsInGridView(GridView gv)
{
long sum = 0;
foreach (GridViewRow row in gv.Rows)
{
sum += SumValuesInRow(row);
}
return sum;
}
public long SumValuesInRow(GridViewRow row)
{
long sum = 0;
foreach (TableCell cell in row.Cells)
{
sum += int.Parse(cell.Text);
}
return sum;
}
public long SumValuesInColumn(GridView gv, int columnIndx)
{
long sum = 0;
foreach (GridViewRow row in gv.Rows)
{
sum += int.Parse(row.Cells[columnIndx].Text);
}
return sum;
}
First method shows the sums on console. The other count the sums for particular GridView. Those counting methods could be written using Linq but for your convenience a left them as simple for and foreach loops.
Hope it solves your problem!
I'm retrieving data from excel and one of the column in excel has '#' like "POLICY #" is the name of the column in excel.
Here is my code
string _policyNoColumn = dtFile.Columns[1].ToString();
string _policyNoRow = string.Empty;
foreach (DataRow _rows in dtFile.Rows)
{
_policyNoRow = _rows[1].ToString();
DataRow[] _rowInFile = dtFile.Select(_policyNoColumn + " = '" + _policyNoRow + "'"); //Check on Excel
if (_rowInFile.Count() == 2)
{
_lstInValid.Add(_policyNoRow); //Invalid
}
}
The value of the _policyNoColumn is "POLICY #". and this what i'm getting.
The expression contains invalid date constant '# = 'V0263680''.
And Here is the source error
Line 501: {
Line 502: _policyNoRow = _rows[1].ToString();
Line 503: DataRow[] _rowInFile = dtFile.Select(_policyNoColumn + " = '" + _policyNoRow + "'"); //Check on Excel
Line 504: if (_rowInFile.Count() == 2)
Line 505: {
Highlighted part is Line 503.
I got the answer
Here what i Did
string _policyNoColumn = "[" + dtFile.Columns[1].ToString() + "]";
I was hoping you could help me with this little problem. I did this to add all my users accounts details to a datagridview and now the colums are all empty?
public DataTable GetResultsTable(string Username)
{
using (SqlDatabaseClient client = SqlDatabaseManager.GetClient())
{
DataRow row = client.ExecuteQueryRow("SELECT * FROM users WHERE username = '" + Username + "'");
DataTable table = new DataTable();
table.Columns.Add("Username".ToString());
table.Columns.Add("Motto".ToString());
table.Columns.Add("Email".ToString());
table.Columns.Add("Homeroom".ToString());
table.Columns.Add("Health".ToString());
table.Columns.Add("Energy".ToString());
table.Columns.Add("Age".ToString());
DataRow dr = table.NewRow();
dr["Username"] = "" + row["username"] + "";
dr["Motto"] = "" + row["motto"] + "";
dr["Email"] = "" + row["mail"] + "";
dr["Homeroom"] = "" + row["home_room"] + "";
dr["Health"] = "" + row["health"] + "";
dr["Energy"] = "" + row["energy"] + "";
dr["Age"] = "" + row["age"] + "";
table.Rows.Add(dr);
return table;
}
}
SqlDatabaseManager.Initialize();
using (SqlDatabaseClient client = SqlDatabaseManager.GetClient())
foreach (DataRow row2 in client.ExecuteQueryTable("SELECT * FROM users").Rows)
{
dataGridView1.DataSource = GetResultsTable((string)row2["username"]);
}
my execute query is
public DataRow ExecuteQueryRow(string CommandText)
{
DataTable DataTable = ExecuteQueryTable(CommandText);
return DataTable.Rows.Count > 0 ? DataTable.Rows[0] : null;
}
public DataRow GetResultsTable(string Username)
{
using (SqlDatabaseClient client = SqlDatabaseManager.GetClient())
{
DataRow row = client.ExecuteQueryRow("SELECT * FROM users WHERE username = '" + Username + "'");
DataRow dr = new DataRow;
dr.Columns.Add("Username".ToString());
dr.Columns.Add("Motto".ToString());
dr.Columns.Add("Email".ToString());
dr.Columns.Add("Homeroom".ToString());
dr.Columns.Add("Health".ToString());
dr.Columns.Add("Energy".ToString());
dr.Columns.Add("Age".ToString());
dr["Username"] = "" + row["username"] + "";
dr["Motto"] = "" + row["motto"] + "";
dr["Email"] = "" + row["mail"] + "";
dr["Homeroom"] = "" + row["home_room"] + "";
dr["Health"] = "" + row["health"] + "";
dr["Energy"] = "" + row["energy"] + "";
dr["Age"] = "" + row["age"] + "";
return dr;
}
}
SqlDatabaseManager.Initialize();
DataTable table = new DataTable();
table.Columns.Add("Username".ToString());
table.Columns.Add("Motto".ToString());
table.Columns.Add("Email".ToString());
table.Columns.Add("Homeroom".ToString());
table.Columns.Add("Health".ToString());
table.Columns.Add("Energy".ToString());
table.Columns.Add("Age".ToString());
using (SqlDatabaseClient client = SqlDatabaseManager.GetClient())
foreach (DataRow row2 in client.ExecuteQueryTable("SELECT * FROM users").Rows)
{
table .Rows.Add( GetResultsTable((string)row2["username"]));
}
DataGridView.DataSourse=table ;