Tuesday, December 21, 2010

Adding object to datagrid

/// <summary>
/// Contains column names.
/// </summary>
List<string> _names = new List<string>();

/// <summary>
/// Contains column data arrays.
/// </summary>
List<double[]> _dataArray = new List<double[]>();


public Form1()
{
InitializeComponent();
// Example column.
_names.Add("Cat");
// Three numbers of cat data
_dataArray.Add(new double[]
{
1.0,
2.2,
3.4
});

// Another example column
_names.Add("Dog");
// Add three numbers of dog data
_dataArray.Add(new double[]
{
3.3,
5.0,
7.0
});
// Render the DataGridView.


}

private void button1_Click(object sender, EventArgs e)
{
dataGridView1.DataSource = GetResultsTable();
}

/// <summary>
/// This method builds a DataTable of the data.
/// </summary>
public DataTable GetResultsTable()
{
// Create the output table.
DataTable d = new DataTable();

// Loop through all process names.
for (int i = 0; i < this._dataArray.Count; i++)
{
// The current process name.
string name = this._names[i];

// Add the program name to our columns.
d.Columns.Add(name);

// Add all of the memory numbers to an object list.
List<object> objectNumbers = new List<object>();

// Put every column's numbers in this List.
foreach (double number in this._dataArray[i])
{
objectNumbers.Add((object)number);
}

// Keep adding rows until we have enough.
while (d.Rows.Count < objectNumbers.Count)
{
d.Rows.Add();
}

// Add each item to the cells in the column.
for (int a = 0; a < objectNumbers.Count; a++)
{
d.Rows[a][i] = objectNumbers[a];
}
}
return d;
}

Reading Excel file in c#

public Object readExcel(string filepath)



{

static string ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;
                    Data Source=C:\EmployeeXLS.xls;
                    Extended Properties=Excel 5.0";


string query = @"Select * From [Sheet1$]";

System.Data.OleDb.OleDbConnection con =
new System.Data.OleDb.OleDbConnection(
ConnectionString);
con.Open();
OleDbDataAdapter da = new OleDbDataAdapter(query, con);
// DataTable dt = new DataTable();
DataSet ds = new DataSet();
da.Fill(ds, "nyNameHere");

//con.Close();
StringBuilder sb = new StringBuilder();
StringBuilder sb2 = new StringBuilder();
List<Employee> _empList = new List<Employee>();
try
{
foreach (DataRow myDataRow in ds.Tables[0].Rows)
{
Employee emp = new Employee();
emp.FName = myDataRow["fname"].ToString();
emp.LName = myDataRow["lname"].ToString();
emp.Age = int.Parse( myDataRow["age"].ToString());
emp.Salary = Double.Parse(myDataRow["wage"].ToString());
_empList.Add(emp);
//Stores info in Datarow into an array
Object[] cells = myDataRow.ItemArray;
//Traverse through each array and put into object cellContent as type Object
//Using Object as for some reason the Dataset reads some blank value which
//causes a hissy fit when trying to read. By using object I can convert to
//String at a later point.
foreach (object cellContent in cells)
{
//Convert object cellContect into String to read whilst replacing Line Breaks with a defined character
string cellText = cellContent.ToString();
cellText = cellText.Replace("\n", "|");
sb.Append("\n" + cellText);
//Read the string and put into Array of characters chars
// richTextBox1.AppendText("\n" + cellText);
}

return )empList;
} 
 

Wednesday, December 15, 2010

Reading an excel file in c#

//Create the Connection String
//You must specify the Provider as is here, I think
//Thre Data Source is the path to your file
//Extended Properties is something to do with excel, use as here

string ConnectionString=@"Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=C:\Test Projects\Excel example\Excel - reading an excel file\ReadThis.xls;
Extended Properties=Excel 5.0";

//Create the connection

System.Data.OleDb.OleDbConnection ExcelConnection =
new System.Data.OleDb.OleDbConnection
(ConnectionString);

//create a string for the query

string ExcelQuery;

//Sheet1 is the sheet name
//create the query:
//read column with heading A from the Excel file

ExcelQuery = "Select A from [Sheet1$]"; // from Sheet1";

//use "Select * ... " to select the entire sheet
//create the command

System.Data.OleDb.OleDbCommand ExcelCommand = new System.Data.OleDb.OleDbCommand(ExcelQuery,ExcelConnection);

//Open the connection

ExcelConnection.Open();

//Create a reader

System.Data.OleDb.OleDbDataReader ExcelReader;
ExcelReader = ExcelCommand.ExecuteReader();

//For each row after the first
//Message box the values in the first column i.e. column 0

while (ExcelReader.Read())
{
MessageBox.Show((ExcelReader.GetValue(0)).ToString());
}
ExcelConnection.Close();

//Try update the file

ExcelQuery = "Update [Sheet1$] set B = 2 where B = 1"; // from Sheet1";

//Create the command to be executed

ExcelCommand = new System.Data.OleDb.OleDbCommand
(ExcelQuery,ExcelConnection);

//Open the connection to the file

ExcelConnection.Open();

//Execute the update

ExcelCommand.ExecuteNonQuery();

//Close the connection

ExcelConnection.Close();