Friday, April 2, 2010

Laoding Data from Database in the Data Grid

First of all we need to create connection of an application with the database add a app.config file in to your solution.

add the code in the main tag of the HTML code present in the app.config file


connectionString="Data Source= XYZ-PC6\SQLEXPRESS;;USER ID=uid;password=pwd;Initial Catalog = umais;"
providerName="System.Data.SqlClient" />


Provide Data Source, data server name, its user ID password and Catalog from the data base

after this need to add the connection string from the CS file

Create a method dataBaseConnection, in the method pass the connection string, create SQL connection and open the connection
string connectionString = (string)ConfigurationManager.ConnectionStrings["_4UnitTesting.Properties.Settings.DBConnectionString"].ConnectionString;
SqlConnection sqlConnection = new SqlConnection(connectionString);
sqlConnection.Open();

SQLDataAdapter is used to fire the SQL Query

SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM DatagridTable", sqlConnection);

initialized the dataset and fill it in the SQL Adapter.
DataSet ds = new DataSet();


ad.Fill(ds);

in the end bind it with datagrid (gvData) datagrid name

gvData.DataSource = ds.Tables[0];

Now after doing this call dataBaseConnection the method from where it will load the data, on click event.....

By this you can load data from the data base, if you want to save the loaded data in CSV file use the previous post of Saving data in CSV file, Need to do same thing...

Thursday, March 11, 2010

Adding Column(s) to a a CSV using datagrid

fileContent has been taken from the previous code, this contain the content of the file. I cast the Datagrid in the DataTable.
dt.Columns.Count counts the column from the grid and add another column in it.

private DataTable addColumn(string fileContent)
{

DataTable dt = (DataTable)gvData.DataSource;
int iColCount = dt.Columns.Count;
dt.Columns.Add("Column" + (iColCount + 1).ToString());
return dt;
}
now this is the button btnAddColumn_Click which add the columns, will call the method addColumn and will add the column in the existing grid

private void btnAddColumn_Click(object sender, EventArgs e)
{
string fileContent = this.readFile(openFileDialog1.FileName);

DataTable dt = this.addColumn(fileContent);
gvData.DataSource = dt;
}

I hope that will be solve your problem.. please let me know if still you feel any problem....

Tuesday, March 9, 2010

Export Datagrid in CSV file in C#

Previously, I wrote a code for Importing any CSV file into a Datagrid, now here is the code for exporting the Datagrid into the CSV file. You can load the CSV file by the code in the previous post, then that grid can be exported back to the CSV file with different name.. Here is the code for it.

This is for saving the CSV file on the particular location

SaveFileDialog sfd = new SaveFileDialog();
String stringFile = string.Empty;
if (sfd.ShowDialog() == DialogResult.OK)
{
stringFile = sf.FileName;
}
else
{
return;
}
StreamWriter streamWriter= new StreamWriter(stringFile, true);

Here I initialized datatable n merge it with the datagrid.
DataTable dt = new DataTable();
dt.Merge((DataTable)gvData.DataSource); gvData is the DataGrid name

For Columns, write function will write the columns after counting.

int iColCount = dt.Columns.Count;
for (int i = 0; i < iColCount; i++)
{
streamWriter.Write(dt.Columns[i]);
if (i < iColCount - 1)
{
streamWriter.Write(",");
}
}
streamWriter.Write(streamWriter.NewLine);

Now write all the rows.
foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < iColCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
streamWriter.Write(dr[i].ToString());
}
if (i < iColCount - 1)
{
streamWriter.Write(",");
}
}
streamWriter.Write(streamWriter.NewLine);
}
streamWriter.Close();

Feel free to ask questions and reports problem in the C# code

Friday, March 5, 2010

Importing CSV file in a Datagrid in C#

Here is the code for Importing a csv file in the Datagrid.

There are 2 helper methods 'readFile' and 'generateDataTable'

readFile opens the csv and returns its contents.

private string readFile(string filePath)
{

StreamReader streamReader = new StreamReader(filePath);
return streamReader.ReadToEnd();

}

generateDataTableFromCSV generates and returns a DataTable for the provided comma seperated string.

private DataTable generateDataTableFromCSV(string fileContent)
{

DataTable dt = new DataTable();
string[] row = fileContent.Split("\r\n".ToCharArray());

string rowstr = row[0];

string[] col = rowstr.Split(',');
int colCount = 1;
foreach (string colstr in col)
{
dt.Columns.Add(new DataColumn("Column" + colCount));
colCount++;
}

dt.AcceptChanges();
return dt;
}

Here is the code on button click event handler that reads the csv file, and displays it in a datagrid.

private void btnLoad_Click(object sender, EventArgs e)
{
string fileContent = this.readFile(openFileDialog1.FileName);

DataTable dt = this.generateDataTableFromCSV(fileContent);

string[] row = fileContent.Split("\r\n".ToCharArray());
foreach(string rowstr in row)
{
DataRow myRow = dt.NewRow();
int colCount = 0;
string [] col = rowstr.Split(',');

foreach (string colstr in col)
{
myRow[colCount] = colstr;
colCount++;
}

dt.Rows.Add(myRow);
}

gvData.DataSource = dt;

}


For StreamReader we need to use the System.IO;
using System.IO;

here is a screenshot of the form


Feel free to ask me questions and report problems in the C# code.