Populating rows with data from a stored procedure using DataTables - c#

I want to populate some fields on a PDF with data from a SQL database, I have a data access class that works but I can't get the values from the rows:
DataAccess DA = new DataAccess();
DataSet S = DA.CashData();
DataTable Cash = S.Tables[0];
DataTable Other = S.Tables[1];
DataTable Check = S.Tables[2];
DataTable Else = S.Tables[3];
string s = "";
foreach (DataRow row in Cash.Rows)
{
foreach (DataColumn col in Cash.Columns)
{
for (int i = 0; i < Cash.Columns.Count; i++)
{
DataRow cashRow = Cash.Rows[i];
s = s + cashRow[0].ToString() + ";";
}
}
Console.ReadLine();
}
string[] data = s.Split(';');
cell32.AddElement(new Paragraph(""));
cell32.AddElement(new Paragraph(data[0]));
cell32.AddElement(new Paragraph(data[1]));
The columns show data but the rows do not

If I understand your source correctly, you have a wrong execution in your loop for the rows, please consider this edited source:
DataAccess DA = new DataAccess();
DataSet S = DA.CashData();
DataTable Cash = S.Tables[0];
DataTable Other = S.Tables[1];
DataTable Check = S.Tables[2];
DataTable Else = S.Tables[3];
string s = "";
foreach (DataRow row in Cash.Rows)
{
for (int i = 0; i < row.Columns.Count; i++)
{
s += row[0].ToString() + ";";
}
Console.ReadLine();
}
string[] data = s.Split(';');
cell32.AddElement(new Paragraph(""));
cell32.AddElement(new Paragraph(data[0]));
cell32.AddElement(new Paragraph(data[1]));

Related

Adding data to data table without filling the column names C#

I am trying to add data from an excel spreadsheet to a data table, I am getting the data no worries and adding it to the tables within the datasets but when I do add it, it fills the column names with the top row. I have tried to set the column names but then it just cuts off the top row of data.
I am fairly new to C#, I'm pretty sure I need to alter the fill method objAdapter1.Fill(objDataset1,tableName); but have no idea how to go about it.
public DataSet readExcel()
{
int x = 0;
string[] Individal_Runs = Directory.GetFiles(#"C:\testfiles");
DataSet objDataset1 = new DataSet();
int iso = 0;
foreach (string s in Individal_Runs)
{
x++;
try
{
String theConnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + s + ";Extended Properties=Excel 12.0 Xml";
OleDbConnection objConn = new OleDbConnection(theConnString);
objConn.Open();
string[] sheetnames = GetExcelSheetNames(String.Format("{0}", s));
int y = 0;
int z = 0;
string tableName;
bool looponce = false;
foreach (string sn in sheetnames)
{
OleDbCommand objCmdSelect = new OleDbCommand(String.Format("SELECT * FROM [{0}]", sn.ToString()), objConn);
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
if( looponce == false)
{
tableName = string.Format("isolations_{0}", iso);
objDataset1.Tables.Add(tableName);
objDataset1.Tables[tableName].NewRow();
DataRow newRow = objDataset1.Tables[tableName].NewRow();
objDataset1.Tables[tableName].Rows.InsertAt(newRow, 0);
looponce = true;
}
else
{
tableName = string.Format("isolations_{0}_{1}", iso,y);
objDataset1.Tables.Add(tableName);
DataRow newRow = objDataset1.Tables[tableName].NewRow();
objDataset1.Tables[tableName].Rows.InsertAt(newRow, 0);
y++;
}
objAdapter1.SelectCommand = objCmdSelect;
objAdapter1.Fill(objDataset1,tableName);
int cols = objDataset1.Tables[tableName].Columns.Count;
for (int i = 0; i < cols; i++)
{
objDataset1.Tables[tableName].Columns[i].ColumnName = i.ToString();
}
z++;
}
iso++;
}

how to add headers from datatable to datagridview in c#

Question edited
I have a datatablethat repeatedly fill by user selection (but the headers of datatable don't change) , using this code I add it's data to a datagridview but the problem is the header of datatable (at
least 50 header that I don't want to add them manually) do not add as well.
public static void GetSelectedFeed(Form2 frm2)
{
if (frm2.FeedSelectListBox.SelectedIndex != -1)
{
string StrCon = System.Configuration.ConfigurationManager.ConnectionStrings["FeedLibraryConnectionString"].ConnectionString;
OleDbConnection Connection = new OleDbConnection(StrCon);
OleDbDataAdapter DataA = new OleDbDataAdapter("Select * from FeedLibrary where ID =" + frm2.FeedSelectListBox.SelectedValue, Connection);
DataTable DTable = new DataTable();
DataA.Fill(DTable);
frm2.SelectedFeeddataGridView.ColumnCount = DTable.Columns.Count;
foreach (DataRow DR in DTable.Rows)
{
frm2.SelectedFeeddataGridView.Rows.Add(DR.ItemArray);
}
frm2.SelectedFeeddataGridView.ColumnHeadersVisible = true;
frm2.SelectedFeeddataGridView.Columns[0].Visible = true;
frm2.SelectedFeeddataGridView.Columns[1].Frozen = true;
frm2.SelectedFeeddataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
}
}
How could I programatically add headers of DataTable to dataGridView ?
this is how the headers of datatable should add to a datagridview
for (int k = 0; k < DTable.Columns.Count; k++)
{
frm2.SelectedFeeddataGridView.Columns.Add(DTable.Columns[k].ColumnName, DTable.Columns[k].Caption);
}

displaying arraylist into a datagridview

I have an arraylist which stores values when a user does an action during runtime. Now im trying to display these values into a datagridview . so what im doing is adding the arraylist items into a datatable and then binding the datatable to the Gridview. but what is being displayed in the datagrid is not the values of the arraylist. here is my code .please help or can anyone direct me to how else this could be done..Thanks in advance
foreach (Class1 aa in ds)
{
checkedListBox1.Items.Add(aa.id + "_" + aa.shape + "_" + aa.color);
DataTable dt = new DataTable();
dt.Columns.Add("Shape");
dt.Columns.Add("Colour");
for (int i = 0; i < ds.Count; i++)
{
dt.Rows.Add(ds);
dt.Rows[i]["Shape"] = ds[i].ToString();
dt.Rows[i]["Colour"] = ds[i].ToString();
dataGridView1.DataSource = dt;
}
dataGridView1.Refresh();
}
}
Maybe you can try creating a DataTable and then adding the required DataRows to it like this :
foreach (Class1 aa in ds)
{
checkedListBox1.Items.Add(aa.id + "_" + aa.shape + "_" + aa.color);
DataTable dt = new DataTable();
dt.Columns.Add("Shape");
dt.Columns.Add("Colour");
for (int i = 0; i < ds.Count; i++)
{
DataRow dRow = dt.NewRow();
dRow["Shape"] = aa.shape;
dRow["Colour"] = aa.color;
dt.Rows.Add(dRow);
}
dataGridView1.DataSource = dt;
dataGridView1.Refresh();
}
}
Hope this helps.

Merge datatables but ignore duplicated rows

I have the following code, its a custom people picker for sharepoint 2010.
It searches by username, but also by the person name.
Because its a contains search, if I try with part of my username: cia
It shows my duplicated rows because that matches the username but also the person name.
this is my code (I cant use LINQ:
protected override int IssueQuery(string search, string groupName, int pageIndex, int pageSize)
{
try
{
// Find any user that has a matching name
var table = ADHelper.ExecuteNameQuery(RootPath, search);
// 20249: Search by username, method was already done, but it was not being called.
var table2 = ADHelper.ExecutesAMAccountNameQuery(search);
table2.Merge(table,);
PickerDialog.Results = table2;
Normally the DataTable.Merge method removes duplicates implicitely. But only when all columns' values are the same.
I'm not sure if there is something simplier(you've mentioned that you cannot use LINQ), but you could merge both and remove the duplicates afterwards:
List<string> dupColumns = new List<string>();
dupColumns.Add("ColumnA");
dupColumns.Add("ColumnB");
table2.Merge(table,);
RemoveDuplicates(table2, dupColumns);
And here the remove-duplicates function:
private void RemoveDuplicates(DataTable table, List<string> keyColumns)
{
Dictionary<string, string> uniquenessDict = new Dictionary<string, string>(table.Rows.Count);
System.Text.StringBuilder sb = null;
int rowIndex = 0;
DataRow row;
DataRowCollection rows = table.Rows;
while (rowIndex < rows.Count)
{
row = rows[rowIndex];
sb = new System.Text.StringBuilder();
foreach (string colname in keyColumns)
{
sb.Append(((string)row[colname]));
}
if (uniquenessDict.ContainsKey(sb.ToString()))
{
rows.Remove(row);
}
else
{
uniquenessDict.Add(sb.ToString(), string.Empty);
rowIndex++;
}
}
}
you should the .ToTable function
here is a sample code
DataTable DT1 = new DataTable();
DT1.Columns.Add("c_" + DT1.Columns.Count);
DT1.Columns.Add("c_" + DT1.Columns.Count);
DT1.Columns.Add("c_" + DT1.Columns.Count);
DataRow DR = DT1.NewRow();
DR[0] = 0;
DR[1] = 1;
DR[2] = 2;
DT1.Rows.Add(DR);
DataTable DT2 = new DataTable();
DT2.Columns.Add("c_" + DT2.Columns.Count);
DT2.Columns.Add("c_" + DT2.Columns.Count);
DT2.Columns.Add("c_" + DT2.Columns.Count);
DT2.Columns.Add("c_" + DT2.Columns.Count);
DR = DT2.NewRow();
DR[0] = 0;
DR[1] = 1;
DR[2] = 2;
DR[3] = 3;
DT2.Rows.Add(DR);
DT1.Merge(DT2);
Trace.IsEnabled = true;
DataTable DT_3=DT1.DefaultView.ToTable(true,new string[]{"c_1","c_2","c_0"});
foreach (DataRow CDR in DT_3.Rows)
{
Trace.Warn("val",CDR[1]+"");//you will find only one data row
}

C# Replacing value in datatable

Scenario: App contains DataGridViews, I am populating the DataGridViews from a Database.
All the data in the Database is encrypted so after I fill my DataTable I need to cycle
through every entry in the DataTable through the decryption methods and place back
in the same spot in the DataTable. How would I do such a task?
Or is there a way I can decrypt the data as it is entering the dataTable?
SQLiteDataAdapter dataAdapter = new SQLiteDataAdapter(query, conn);
SQLiteCommandBuilder commandBuilder = new SQLiteCommandBuilder(dataAdapter);
DataTable dataTable = new DataTable();
dataTable.Locale = System.Globalization.CultureInfo.Invaria…
dataAdapter.Fill(dataTable);
//Decrypt cells
int i;
foreach (DataRow row in dataTable.Rows)
{
i = 0;
foreach (var item in row.ItemArray)
{
//This doesn't work
row.ItemArray[i] = Crypto.Decrypt(item.ToString());
i++;
}
}
return dataTable;
for (int i = 0; i < dataTable.Rows.Count; i++)
{
for (int j = 0; j < dataTable.Columns.Count; j++)
{
dataTable.Rows[i][j] = Crypto.Decrypt(dataTable.Rows[i][j].ToString());
}
}

Categories