Datatable does not take initial spaces, so when i insert it into database and retrieve it by select statement and display it on page using stringBuilder, Initial spaces are gone and text does not appear on screen as it is written in textbox
DataTable1.Rows[0][0]=TextBox1.Text;
This is how I insert into database
public static void Insert(DataTable table)
{
StringBuilder Col = new StringBuilder();
StringBuilder Val = new StringBuilder();
string Query, finalVal;
int i, j;
int count = 0;
int ColumnCount = table.Columns.Count;
for (i = 0; i < ColumnCount; i++)
{
if (table.Rows.OfType<DataRow>().Any(r => !r.IsNull(table.Columns[i].ColumnName)))
{
Col.Append(table.Columns[i].ColumnName);
Col.Append(",");
count++;
}
}
Col.Remove(Col.Length - 1, 1);
string[] columnName = Col.ToString().Split(',');
foreach (DataRow r in table.Rows)
{
Val.Append(",(");
for (j = 0; j < count; j++)
{
if (r[columnName[j]] != null)
{
Val.Append("'" + r[columnName[j]] + "'");
Val.Append(",");
}
else
{
Val.Append("null,");
}
}
Val.Append(")");
Val.Remove(Val.Length - 2, 1);
}
finalVal = Val.ToString().Substring(1);
Query = "Insert into " + table.TableName + "(" + Col + ")" + "Values" + finalVal;
EduDB.ExecuteNonQuery(Query);
}
You must be trimming the string befor inserting into database. Please check that out
Related
I have a program that runs a SQL query and returns data to a datagridview.
I then write the data to a csv file which works great.
However, I need to add a line in the csv for each item based on the quantity of the record.
The first record (highlighted in blue) has a quantity of 12, so I need to insert 12 lines containing the information from the first record, and so forth down the list.
This is what I would like to show :
Below is the code that I am using to create the csv file.
string strValue = string.Empty;
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
for (int j = 0; j < dataGridView1.Rows[i].Cells.Count; j++)
{
if (!string.IsNullOrEmpty(dataGridView1[j, i].Value.ToString()))
{
if (j > 0)
strValue = strValue + "," + dataGridView1[j, i].Value.ToString();
else
{
if (string.IsNullOrEmpty(strValue))
strValue = dataGridView1[j, i].Value.ToString();
else
strValue = strValue + Environment.NewLine + dataGridView1[j, i].Value.ToString();
}
}
}
}
string strFile = #"\\\\Path_To_CSV\\DynamicsPartsLabels.csv";
if (File.Exists(strFile) && !string.IsNullOrEmpty(strValue))
{
File.WriteAllText(strFile, strValue);
}
Is there a way to read the last column in the datagridview (Quantity) and create a line in a csv for each record based on the number in that column?
Try changing the code to:
StringBuilder rows = new StringBuilder();
var row = string.Empty;
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
row = string.Join(",", dataGridView1.Rows[i].Cells.Cast<DataGridViewCell>().Select(x => x.Value));
int.TryParse(dataGridView1.Rows[i].Cells["Quantity"].Value?.ToString(), out var quantity);
for (int q = 0; q < quantity; q++)
{
rows.AppendLine(row);
}
}
var strValue = rows.ToString();
I am reading an excel that contains a matrix table like the following:
I need to enter the values into an SQL table with the following syntax:
insert into t values (1,18,1.943)
insert into t values (1,18,1.524)
insert into t values (1,18,1.395)
etc
what I tried to do is:
DataTable dt = new DataTable();
dt = ReadExcelFile(Server.MapPath("/Migration/" + txtExcelName.Text + ".xlsx"), false);
if (dt.Rows.Count > 0)
{
StringBuilder str = new StringBuilder();
DataRow myrow = null;
DataColumn mycol = null;
for (int i = 0; i < dt.Rows.Count; i++)
{
myrow = dt.Rows[i];
if (i == 0)
{
myrow = dt.Rows[i +1];
}
for (int j = 1; j < dt.Columns.Count; j++)
{
mycol = dt.Columns[j];
try
{
str.Append("insert into HousingLoanInsuranceRate values (" + dt.Rows[i][mycol] + "," + myrow[0] + ",'" + dt.Rows[i+1][mycol] + "',0,0)");
str.Append("<br/>");
}
catch (Exception ex)
{
}
}
}
litMessage.Text += str.ToString();
}
But it seems my code is not returning the wished result
Appreciate your help.
for (int i = 1; i < dt.Rows.Count; i++) // start from 1
{
myrow = dt.Rows[i];
//if (i == 0)
//{
// myrow = dt.Rows[i +1];
//}
for (int j = 1; j < dt.Columns.Count; j++)
{
try
{
// CHANGES MADE HERE ---------------------------------------vvvvvvvvvvvvv--------------------------vvvvvvvv
str.Append("insert into HousingLoanInsuranceRate values ("+ dt.Rows[0][j] + "," + myrow[0] + "," + myrow[j] + ",0,0)");
str.Append("<br/>");
}
catch (Exception ex)
{
}
}
}
This should fix your problem.
However, be aware that this code is vulnerable to SQL injection. Consider using parameterized query.
How can I export my datagrid to CSV correctly? Why are the Rows in different columns?
ExportToCsv function return:
Column Headers:
"SR #;8D Report Requested;Status (ASSIST);In R&D;BTQ NUMBER;Priority;Target Date;Implementation Date;Status (BTQ)"
Rows: WRONG!
"1-3271406718;yes;yes;BTQ00153254;6 - Enhancement;22.02.2014;09.09.2014 ;COMPLETED;Eng. wait"
How it should be:
Column Headers:
"SR #;8D Report Requested;Status (ASSIST);In R&D;BTQ NUMBER;Priority;Target Date;Implementation Date;Status (BTQ)"
Rows:
"1-3271406718;yes;Eng. wait;yes;BTQ00153254;6 - Enhancement;22.02.2014;09.09.2014 ;COMPLETED"
here my code:
string CsvFpath = saveDLG.FileName;
StreamWriter csvFileWriter = new StreamWriter(CsvFpath, false);
string columnHeaderText = "";
int countColumn = dgvView.Columns.Count - 1;
if (countColumn >= 0)
{
columnHeaderText = (dgvView.Columns[0].Header).ToString();
}
//Writing column headers
for (int i = 1; i <= countColumn; i++)
{
columnHeaderText = columnHeaderText + ';' + (dgvView.Columns[i].Header).ToString();
}
csvFileWriter.WriteLine(columnHeaderText);
// Writing values row by row
for (int i = 0; i <= dgvView.Items.Count - 2; i++)
{
string dataFromGrid = "";
for (int j = 0; j <= dgvView.Columns.Count - 1; j++)
{
if (j == 0)
{
dataFromGrid = ((DataRowView)dgvView.Items[i]).Row.ItemArray[j].ToString();
}
else
{
dataFromGrid = dataFromGrid + ';' + ((DataRowView)dgvView.Items[i]).Row.ItemArray[j].ToString();
}
}
csvFileWriter.WriteLine(dataFromGrid);
}
csvFileWriter.Flush();
csvFileWriter.Close();
Try it with Linq. It's simpler and easy to read:
public string DataGridToCSV(string delimiter = ";")
{
var sb = new StringBuilder();
var headers = myDataGridView.Columns.Cast<DataGridViewColumn>();
sb.AppendLine(string.Join(delimiter, headers.Select(column => "\"" + column.HeaderText + "\"").ToArray()));
foreach (DataGridViewRow row in myDataGridView.Rows)
{
var cells = row.Cells.Cast<DataGridViewCell>();
sb.AppendLine(string.Join(delimiter, cells.Select(cell => "\"" + cell.Value + "\"").ToArray()));
}
return sb.ToString();
}
Just save the String as *.csv File and you're done.
I want to remove in each line from specific values the apostrophes.
This is my code for writing into a text file:
for (int a = 0; a < checkedListBox1.CheckedItems.Count; a++)
{
DataTable ExportTable = new DataTable();
//Debug.WriteLine(checkedListBox1.CheckedItems[a].ToString());
string SelectLines =
"SELECT Identifier,
TestID,
Description,
Enabled,
StringLimit,
LowLimit,
HighLimit,
LimitType,
Unit,
Parameters
FROM specifications
where Identifier = '" + checkedListBox1.CheckedItems[a] + "'";
ExportTable = ObjSqlAccess.GetDataTableFromTable(SelectLines);
int rowcount = ExportTable.Rows.Count;
int columncount = ExportTable.Columns.Count;
int rw = 0;
int clm = 0;
writeText.WriteLine("\r\n\r\n[" + checkedListBox1.CheckedItems[a].ToString() + "]" + "\r\nCount = " + (rowcount - 1));
for (rw = 0; rw < rowcount - 1; rw++)
{
string test = "";
for (clm = 0; clm < columncount - 1; clm++)
{
test += ExportTable.Rows[rw][clm].ToString();
test += "','";
}
writeText.WriteLine((rw + 1) + "=(Identifier,TestID,Description,Enabled,StringLimit,LowLimit,HighLimit,LimitType,Unit,Parameters) VALUES ('" + removeThis + "')");
}
writeText.Flush();
writeText.Close();
writeText.Dispose();
And for instance, I want to remove the apostrophes from each line from only these values: 1, 0 , 0 before writing it to a text file. Or to be more specific, only the values that are assigned to Enable, LowLimit and HighLimit column.
Does anyone has an idea of how to proceed? I hope my question is clear enough.
Try this:
for (clm = 0; clm < columncount - 1; clm++)
{
DataColumn col = ExportTable.Columns[clm];
test += ExportTable.Rows[rw][clm].ToString();
if (col.DataType == bool || col.DataType == Int32) //Add other types that dont require single quotes to if statement
{
test += ",";
}
else
{
test += "','";
}
}
First, I would change the way you're writing the string so it doesn't care if there are single quotes, or anything else, in the variable you pass for VALUES.
writeText.WriteLine((rw + 1) + "=(Identifier,TestID,Description,Enabled,StringLimit,LowLimit,HighLimit,LimitType,Unit,Parameters) VALUES (" + test + ")");
Also worth noting is I don't think your loops will work correctly. When you use a count in a for loop, the count is already 1-indexed. So, if you do columnCount = ExportTable.Columns.Count;, your loop should be for (int i = 0; i < columnCount; i++). An easy way to remember is index is 0-based, but count is 1-based.
I would also use a string builder instead. Then in your loop just do a check for those columns:
string test = "";
for (clm = 0; clm < columncount; clm++)
{
StringBuilder sb = new Stringbuilder();
sb.Append(ExportTable.Rows[rw][clm].ToString());
if (clm != 3 && clm != 5 && clm != 6)
{
sb.Insert(0,"'");
sb.Append("'");
}
test += sb;
if (clm != columncount - 1) // add a comma if it's not the last column
{
test += ",";
}
}
I have a data in data table with say 4 columns.Out of those 10 columns first column contains the date.The data in the table is in the form :
I/p
"15/12/2010",username,24,No
"16/12/2010",username,24,No
"17/12/2010",username,24,No
"18/12/2010",username,24,No
"19/12/2010",username,24,No
"20/12/2010",username,25,No
"21/12/2010",username,24,yes
"22/12/2010",username,24,No
"23/12/2010",username,24,No
"24/12/2010",username,24,No
"25/12/2010",username,24,No
"26/12/2010",Prakhar,24,No
"27/12/2010",username,24,No
"28/12/2010",username,24,No
We have to bind the o/p with the repeater.
For aforemenioned i/p the output should be :
O/P
"15/12/2010 - 20/12/2010",username,24,No
"21/12/2010 - 21/12/2010",username,24,Yes
"22/12/2010 - 25/12/2010",username,24,no
"26/12/2010 - 26/12/2010",username,24,no
"27/12/2010 - 28/12/2010",username,24,no
I.e. we are clubbing all the dates whose corresponsing column values are matching.
We have to write a c# code for it.
First I have created a new Datatable for our final result:
DataTable dtInventoryTable = new dtInventoryTable();
dtInventoryTable.Columns.Add("RateDate", typeof(string));
dtInventoryTable.Columns.Add("RatePlanId", typeof(string));
dtInventoryTable.Columns.Add("RoomTypeId", typeof(string));
private DataTable DisplayInventoryDetails(DataTable dtInventoryDetail)
{
for (int i = 0; i < dtInventoryDetail.Rows.Count; i++)
{
String[] row = new String[dtInventoryDetail.Columns.Count];
String[] row1 = new String[dtInventoryDetail.Columns.Count];
string str=string.Empty;
int h=0;
str = dtInventoryDetail.Rows[i][0].ToString() + " - " +dtInventoryDetail.Rows[i]0].ToString();
for (int j = i+1;j< dtInventoryDetail.Rows.Count; j++)
{
for (int x = 1; x < dtInventoryDetail.Columns.Count; x++)
{
row[x] = dtInventoryDetail.Rows[i][x].ToString();
}
for (int y = 1; y < dtInventoryDetail.Columns.Count; y++)
{
row1[y] = dtInventoryDetail.Rows[j][y].ToString();
}
bool result = ArraysEqual(row, row1);
if (!result)
{
dtInventoryTable = GetRoomRateTable(row, str);
i = j-1;
h = j;
break;
}
else
str= dtInventoryDetail.Rows[i][0].ToString() + " - " + dtInventoryDetail.Rows[j][0].ToString();
h = j;
}
}
if (h >= dtInventoryDetail.Rows.Count-1)
{
dtInventoryTable = GetRoomRateTable(row, str);
break;
}
}
return dtInventoryTable;
}
private DataTable GetRoomRateTable(String[] row,string str)
{
row[0] = str;
dtInventoryTable.LoadDataRow(row, true);
return dtInventoryTable;
}