I am trying to run an insert statement into a DataTable (I'm doing it this way so that all functions in the statement will be executed so I can get the intended values)
private void insertintoDT(DataTable destination, string InsertStatement)
{
SqlCommand comm = new SqlCommand(InsertStatement);
SqlDataReader reader = new SqlDataReader();
destination.Load(reader);
}
}
This DataTable will then be loaded into a DataGrid so I can see the values that will be inserted. I tried breaking up the insert statement like so:
private void breakupInsert(String insert)
{
DataTable dt = new DataTable();
dgvInsert.Rows.Clear();
string stemp = insert;
int len = stemp.Length;
int itemp = 0;
stemp = stemp.Remove(0, 12);
itemp = stemp.IndexOf("VALUES") - 1;
gvtable = stemp.Substring(0, itemp);
stemp = stemp.Remove(0, itemp + 9);
int itemcount = stemp.Count(x => x == ',') + 1;
string[] values = new string[itemcount - 1];
//populate values
int h = 0;//Used as a start index
int itemc = 0; //item index
for (int k = 0; k < stemp.Length; k++)
{
if (k == stemp.Length - 2)
{
values[itemc] = ExecuteSQL(stemp.Substring(h, (k + 1) - h));
break;
}
else
if (stemp.Substring(k, 2) == (", "))
{
itemp = stemp.IndexOf(", ");
values[itemc] = ExecuteSQL(stemp.Substring(h, k - h));
h = k + 2;
itemc = itemc + 1;
k = k + 1;
}
else if (stemp.Substring(k, 2) == ("),"))
{
itemp = stemp.IndexOf("),");
values[itemc] = ExecuteSQL(stemp.Substring(h, k - h));
h = k + 2;
itemc = itemc + 1;
k = k + 1;
}
else if (stemp.Substring(k, 2) == ("',"))
{
itemp = stemp.IndexOf("',");
values[itemc] = ExecuteSQL(stemp.Substring(h, (k - h) + 1));
h = k + 2;
itemc = itemc + 1;
k = k + 1;
}
}
for (int j = 0; j < values.Length; j++)
{
this.dgvInsert.Rows.Insert(j, j + 1, values[j], values[j].Length);
}
}
However this breaks when a function is in the insert statement ( cast for example)
Is there a way to do it or is this a lost cause?
To Clarify:
I'm essentially trying to provide the user with a text box that they can paste an SQL statement into, this statement will then be reflected in a datagrid. So if an insert statement is put in, the datatable will reflect the values that are being inserted. But without ever inserting them into the database.
Queries are database-specific, so parsing queries is done by a database-specific component, probably on the database server and otherwise the ADO.NET driver for that database.
You could use SQLite to create an in-memory database, so your end users won't have to set up a separate database (it does require SQLite dll's shipped with your application), however using that approach forces you to use the SQLite dialect, and some queries might not work if you attempt to use them on a different database. It does sound to me like the easiest way out though.
This answer suggests using the entity framework to parse queries, but I don't know if it can help you update the datatable. I haven't tried this myself but it might be worth looking into.
Related
I'm a VB.Net coder, but trying to approach C# programming
In VB.NET I can write like this without any hassle
For i As Integer = 0 To dt.Rows.Count - 1 'dt is datatable
dgv.Rows.Add()
dgv.Rows(i).Cells("Sno").Value = i + 1
dgv.Rows(i).Cells("itemcode").Value = dt.Rows(i)("itemcode").ToString.Trim
dgv.Rows(i).Cells("itemname").Value = dt.Rows(i)("itemname")
Next
But when I code in C#
for (int i = 0; i <= dt.Rows.Count-1; i++) //dt is datatable
{
DG.Rows.Add();
DG.Rows(i).Cells("Sr").Value = i + 1;
DG.Rows(i).Cells("Itemcode").Value = dt.rows(i)("itemcode");
}
DG.Rows(i).Cells("Sr").Value = i + 1; gives error
Non-invocable member 'DataGridView.Rows' cannot be used like a
method.
What am i doing wrong?
In C# you should use brackets [] instead of parenthesis ():
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
DG.Rows.Add();
DG.Rows[i].Cells["Sr"].Value = i + 1;
DG.Rows[i].Cells["Itemcode"].Value = dt.Rows[i]["itemcode"];
}
Try Using [] brackets instead of () :
e.g.
DG.Rows[i].Cells["Sr"].Value = i + 1;
instead of
DG.Rows(i).Cells("Sr").Value = i + 1;
Hey guys I need to insert empty rows below a certain row in an excel and then add data into those empty rows I inserted...
So far I am able to create empty rows but I am having a hell of a time trying to figure out how to set Range.Value to an array of type String
Method for inserting Rows:
private void shiftRows(int from, int numberof)
{
from++;
Range r = oXL.get_Range("A" + from.ToString(), "A" + from.ToString()).EntireRow;
for (int i = 0; i < numberof; i++)
r.Insert(Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftDown);
}
// so this would shift the below rows by numberof times.
This method is currently what I am stuck on... which is inserting an array into the new rows one row at a time
public void inputRowData(string[] data, int rds)
{
int bestRow = getRowByRDS(rds);
string val = getValueOfCell(bestRow, 6);
if (val == null || val.Equals(""))
{
shiftRows(bestRow, data.Length);
string[] formatedData = formatOutput(bestRow, data);
for (int i = 0; i < formatedData.Length; i++)
{
Range r = oSheet.get_Range((bestRow + i).ToString() + ":" + (bestRow + i).ToString());
r.set_Value(formatedData[i].Split('\t'));
// have tried r.Value = formatedData[i].Split('\t')
// formatedData is an array of string which contains data for each cell seperated by a tab
}
}
else
{
Console.WriteLine("Line has some information already, skipping 1 more");
shiftRows(bestRow, data.Length + 1);
}
}
I strongly advise you:
NOT to insert rows but just write empty row instead (safety and performance)
to set a big array object and do only ONE write in excel (performance)
example (i kept the shiftrows but you should really get rid of it):
public void inputRowData(string[] data, int rds)
{
int bestRow = getRowByRDS(rds);
string val = getValueOfCell(bestRow, 6);
if (val == null || val.Equals(""))
{
shiftRows(bestRow, data.Length);
string[] formatedData = formatOutput(bestRow, data);
// transform formated data into string[,]
var string[][] splitedData = formatedData.Select(s => s.Split('\t')).ToArray();
var colCount = splitedData.Max(r => r.Lenght);
var excelData = new string[splitedData.Length, colCount]
for (int i = 0; i < splitedData.Length; i++)
{
for (int j = 0; j < splitedData[i].Length; j++)
{
excelData[i,j] = splitedData[i][j];
}
}
oSheet.get_Range("A" + bestRow.ToString()).Resize(splitedData.Length, colCount).Value = excelData;
}
else
{
Console.WriteLine("Line has some information already, skipping 1 more");
shiftRows(bestRow, data.Length + 1);
}
}
I tried a method for the question Asked.
public DataTable allSupportPoints(DataTable createPath, double rMax, double interval, int curveType)
{
List <DataTable> theCornerCurves = cornerCurves(createPath, rMax, interval, curveType);
DataTable curvePoints = CustomMerge(theCornerCurves);
double X1 = Convert.ToDouble(createPath.Rows[0][1]);
double Y1 = Convert.ToDouble(createPath.Rows[0][2]);
double X2, Y2;
int count = curvePoints.Rows.Count;
double theDistance;
int pointInsert;
for (int i = 0; i < count;)
{
X2 = Convert.ToDouble(theCornerCurves[i].Rows[0][0]);
Y2 = Convert.ToDouble(theCornerCurves[i].Rows[0][0]);
theDistance = distance(X1,Y1,X2,Y2);
int j=0;
if ( theDistance> interval)
{
pointInsert = Convert.ToInt32 (theDistance / interval);
DataTable temp = straightLineGenerator(X1, Y1, X2, Y2,interval);
for (j = 0; j < temp.Rows.Count; j++)
{
var rowTemp = temp.NewRow();
rowTemp.ItemArray = temp.Rows[j].ItemArray.Clone() as object[];
curvePoints.Rows.InsertAt(rowTemp, i + j);
}
}
X1=Convert.ToDouble(curvePoints.Rows[i+j][0]);
Y1 = 0;
count = curvePoints.Rows.Count;
i = i + 1;
}
return curvePoints;
}
I get This runTime Error: This row already belongs to another table.
I have tried different methods to Insert yet the error is same, i referred some posts also but it doesnt seem to work
Please help!!!!
Change this:
var rowTemp = temp.NewRow();
to this:
var rowTemp = curvePoints.NewRow();
In fact the row must be created by the same table you want to add it
This part of your code:
for (j = 0; j < temp.Rows.Count; j++)
{
var rowTemp = temp.NewRow();
rowTemp.ItemArray = temp.Rows[j].ItemArray.Clone() as object[];
curvePoints.Rows.InsertAt(rowTemp, i + j);
}
is incorrect. First you're adding new row to temp, and then trying to insert it into curvePoints. Since it already belongs to temp datatable - you're getting exception you've mentioned.
This code can be simplified as
for (j = 0; j < temp.Rows.Count; j++)
curvePoints.ImportRow(temp.Rows[j]);
But note: ImportRow inserts row at last position, so if you really need to insert row into specific position like you're doing - just leave your code as is and only change var rowTemp = temp.NewRow(); to var rowTemp = curvePoints.NewRow();
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 += ",";
}
}
Hello every one I am working on my college project I am trying to make an windows application using sql server 2008 and visual c#. I am using grid view for input. Problem is when a new row is added the string does not increment. I mean my empid is at row[i] and cell[0] when i go on to next row the empid is same as in previous row according to my code it should increase by 1 from initial value The result which i want is
row[0]cell[0] = emp6;
row[1]cell[0] = emp7;
row[2]cell[0] = emp8;
row[3]cell[0] = emp9;
and yes i don't want to use row count (digit) as a Id integer because of duplicacy of employeeID in database so to avoid this i am using SQL COUNT to get initial value for ID.
here is my code please help me soon
void emp_id_generator(DataGridView dataGridView1)
{
if (dataGridView1 != null)
{
for (int count = 0; (count <= (dataGridView1.Rows.Count - 2)); count++)
{
int j = 6; //this is what i want to increment
Label l = new Label();
l.Text = "EmpID" + (j);
dataGridView1.Rows[count].Cells[0].Value = l.Text;
j=j+1;
}
}
}
Try this way.
J must be initialized outside the loop.
Have a nice day.
void emp_id_generator(DataGridView dataGridView1)
{
if (dataGridView1 != null)
{
int j = 6; //this is what i want to increment
for (int count = 0; (count <= (dataGridView1.Rows.Count - 2)); count++)
{
Label l = new Label();
l.Text = "EmpID" + (j);
dataGridView1.Rows[count].Cells[0].Value = l.Text;
j=j+1;
}
}
}