Converting DataTable to string type - c#

I have a function like this
public DataTable GetAllPrimaryKeyTables(string localServer, string userName, string password, string selectedDatabase)
{
// Create the datatable
DataTable dtListOfPrimaryKeyTables = new DataTable("tableNames");
SqlConnectionStringBuilder objConnectionString = new SqlConnectionStringBuilder();
objConnectionString.DataSource = localServer; ;
objConnectionString.UserID = userName;
objConnectionString.Password = password;
objConnectionString.InitialCatalog = selectedDatabase;
// Query to select primary key tables.
string selectPrimaryKeyTables = #"SELECT
TABLE_NAME
AS
TABLES
FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE
CONSTRAINT_TYPE = 'PRIMARY KEY'
AND
TABLE_NAME <> 'dtProperties'
ORDER BY
TABLE_NAME";
// put your SqlConnection and SqlCommand into using blocks!
using(SqlConnection sConnection = new SqlConnection(objConnectionString.ConnectionString))
using(SqlCommand sCommand = new SqlCommand(selectPrimaryKeyTables, sConnection))
{
try
{
// Create the dataadapter object
SqlDataAdapter sDataAdapter = new SqlDataAdapter(selectPrimaryKeyTables, sConnection);
// Fill the datatable - no need to open the connection, the SqlDataAdapter will do that all by itself
// (and also close it again after it is done)
sDataAdapter.Fill(dtListOfPrimaryKeyTables);
}
catch(Exception ex)
{
//All the exceptions are handled and written in the EventLog.
EventLog log = new EventLog("Application");
log.Source = "MFDBAnalyser";
log.WriteEntry(ex.Message);
}
}
// return the data table to the caller
return dtListOfPrimaryKeyTables;
}
Then I wanted to get the return type as string and not as DataTable so I did this..
public string GetAllPrimaryKeyTables(string ConnectionString)
{
string result = string.Empty;
// Query to select primary key tables.
string selectPrimaryKeyTables = #"SELECT
TABLE_NAME
AS
TABLES
FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE
CONSTRAINT_TYPE = 'PRIMARY KEY'
AND
TABLE_NAME <> 'dtProperties'
ORDER BY
TABLE_NAME";
// put your SqlConnection and SqlCommand into using blocks!
using(SqlConnection sConnection = new SqlConnection(ConnectionString))
using(SqlCommand sCommand = new SqlCommand(selectPrimaryKeyTables, sConnection))
{
try
{
// Create the dataadapter object
SqlDataAdapter sDataAdapter = new SqlDataAdapter(selectPrimaryKeyTables, sConnection);
DataTable dtListOfPrimaryKeyTables = new DataTable("tableNames");
// Fill the datatable - no need to open the connection, the SqlDataAdapter will do that all by itself
// (and also close it again after it is done)
sDataAdapter.Fill(dtListOfPrimaryKeyTables);
using(StringWriter sw = new StringWriter())
{
dtListOfPrimaryKeyTables.WriteXml(sw);
result = sw.ToString();
}
}
catch(Exception ex)
{
//All the exceptions are handled and written in the EventLog.
EventLog log = new EventLog("Application");
log.Source = "MFDBAnalyser";
log.WriteEntry(ex.Message);
}
}
// return the data table to the caller
return result;
}
But this is not returning the string which it should ...
Can you direct me to the point that required modifications.

Instead of a StringWriter, use a StringBuilder, then you can use the Write and WriteLine methods.

If you want a comma seperated list, you could use something like below.
private string GetList(ds)
{
var result = string.Empty;
for(int i = 0; i < ds.Rows.Count; i++)
{
result += ds.Row[i][0] + ",";
}
result = result.Trim(',');
return result;
}
Hope this helps.

Related

Get the Row values from a excel based on the column Value

I am trying to a get the Row values from a excel sheet, based on the column Value.
e.g. I have CutsomerID as lets say 5 , so I want First name 5, last Name 5 and Address 5
I am converting whole excel sheet into DataTable and then trying to read on each DataRow, when I get CustomerID as 5, I copy all the values and break from the loop
Here is my code and it is working fine as well, but I was wondering is there any way to optimise it.
Here is my Code.
public ExcelData GetDataByCustomerID(String excelFilePath, String customerID)
{
OleDbConnectionStringBuilder connectionStringBuilder = new OleDbConnectionStringBuilder();
connectionStringBuilder.Provider = "Microsoft.ACE.OLEDB.12.0";
connectionStringBuilder.DataSource = excelFilePath;
connectionStringBuilder.Add("Mode", "Read");
const string extendedProperties = "Excel 12.0;IMEX=1;HDR=YES";
connectionStringBuilder.Add("Extended Properties", extendedProperties);
String connectionString = connectionStringBuilder.ToString();
// Create connection object by using the preceding connection string.
using( var objConn = new OleDbConnection(connectionString))
{
objConn.Open();
// Get the data table contaning the schema guid.
DataTable excelSheetsDataTable = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (excelSheetsDataTable == null)
return null;
// get all the tables in the Sheet
List<String> excelSheets = (from DataRow row in excelSheetsDataTable.Rows select row["TABLE_NAME"].ToString()).ToList();
// Our data is on First sheet only
OleDbCommand _oleCmdSelect = new OleDbCommand(#"SELECT * FROM [" + excelSheets[0] + "]", objConn);
OleDbDataAdapter oleAdapter = new OleDbDataAdapter();
oleAdapter.SelectCommand = _oleCmdSelect;
DataTable newDataTable = new DataTable();
oleAdapter.FillSchema(newDataTable, SchemaType.Source);
oleAdapter.Fill(newDataTable);
if (newDataTable.Columns.Contains("CustomerID"))
{
foreach (DataRow rowValue in newTB.Rows)
{
if ((string) rowValue["CustomerID"] == customerID)
{
var data = new ExcelData
{
customerFirstName = rowValue["Customer_First_ Name"].ToString(),
customerLastName = rowValue["Customer_Last_Name"].ToString(),
customerAddress = rowValue["Customer_Address"].ToString(),
};
return data;
}
}
String message = String.Format("The CustomerID {0} not found in Excel file {1}", customerID, excelFilePath);
MessageBox.Show(message);
}
else
{
String message = String.Format("The Column CustomerID not found in Excel file {0}", excelFilePath);
MessageBox.Show(message);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return null;
}
public class ExcelData
{
public String customerID;
public String customerFirstName;
public String customerLastName;
public String customerAddress;
}
Change your select query to like below -
#"SELECT * FROM [" + excelSheets[0] + "] WHERE CustomerID=<your_value>"
Courtesy msdn web site:
Link: MSDN
DataTable dt;
private void button1_Click(object sender, EventArgs e)
{
try
{
openFileDialog1.ShowDialog();
string connectionString = string.Format("Provider = Microsoft.Jet.OLEDB.4.0;Data Source ={0};Extended Properties = Excel 8.0;", this.openFileDialog1.FileName);
var con = new OleDbConnection(connectionString);
var cmd = new OleDbCommand("select * from [sheet1$] where [MRN#]=#c", con);
cmd.Parameters.Add("#c", "33264");
con.Open();
var dr = cmd.ExecuteReader();
if (dr.HasRows)
{
dt = new DataTable();
dt.Load(dr);
}
dr.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
DataGridView dv = new DataGridView();
this.Controls.Add(dv);
dv.DataSource = dt;
}
}
EDIT:
As per your code you should try the below lines of code:
OleDbCommand _oleCmdSelect = new OleDbCommand(#"SELECT * FROM [" + excelSheets[0] + "]" + " Where [CustomerID#] = #custID" , objConn);
_oleCmdSelect.Parameters.Add("#custID", customerID);
OleDbDataAdapter oleAdapter = new OleDbDataAdapter();
oleAdapter.SelectCommand = _oleCmdSelect;

Databind a dropdownlist

When I try to databing dropdownlist, got this: system.data.datarowview
what do I wrong?
string strQuery = "Select Item FROM Calendar Where UserD="Test";
SqlConnection myConn;
SqlDataAdapter sqlDa = new SqlDataAdapter(strQuery,myConn);
DataTable sqlTa = new DataTable("Test");
da.Fill(sqlTa);
ddlList.DataSource = sqlTa;
ddlList.DataBind();
string strQuery = "Select Item FROM Calendar Where UserD='Test'";
Note you need to use single quotations around the string, as in your code you didn't finish the inital string ever, so the rest of the code just became part of strQuery.
In addition if you bring back more than one field in the future, when you bind a dropdown list you need to specify which field from the database is the value and which is the displayed text.
ddlList.DataSource = sqlTa;
ddlList.DataValueField = "ValueFieldFromDatabaseResults";
ddlList.DataTextField = "ShownTextFieldFromDatabaseResults";
ddlList.DataBind();
You need to tell it what fields to use as value and text.
ddlList.DataSource = sqlTa;
ddlList.DataValueField = "ValueField";
ddlList.DataTextField = "TextField";
ddlList.DataBind();
And your select statement is missing a ". It should be:
"Select Item FROM Calendar Where UserD='Test'"
An Example being:
As ryan pointed out if you are pulling back one field then you can just do:
DataTable dtTable = new DataTable();
try
{
using (SqlConnection sqlConnection = new SqlConnection("Your connection"))
{
using (SqlCommand sqlCommand = new SqlCommand("Select Item FROM Calendar Where UserD='Test'", sqlConnection))
{
sqlConnection.Open();
using (SqlDataReader sqlDataReader = sqlCommand.ExecuteReader())
{
dtTable.Load(sqlDataReader);
sqlDataReader.Close();
}
}
}
}
catch (Exception error)
{
throw error;
}
ddlList.DataSource = dtTable;
ddlList.DataBind();
But if you have more then one field then you can do this:
DataTable dtTable = new DataTable();
try
{
using (SqlConnection sqlConnection = new SqlConnection("Your connection"))
{
using (SqlCommand sqlCommand = new SqlCommand("Select Item, id FROM Calendar Where UserD='Test'", sqlConnection))
{
sqlConnection.Open();
using (SqlDataReader sqlDataReader = sqlCommand.ExecuteReader())
{
dtTable.Load(sqlDataReader);
sqlDataReader.Close();
}
}
}
}
catch (Exception error)
{
throw error;
}
ddlList.DataSource = dtTable;
ddlList.DataValueField = "id";
ddlList.DataTextField = "item";
ddlList.DataBind();
add this line way
ddlList.DataSource = sqlTa;
ddlList.DataValueField = "ValueFieldFromDatabaseResults";
ddlList.DataTextField = "ShownTextFieldFromDatabaseResults";
ddlList.DataBind();
then u miss connection string for
SqlConnection myConn="must add your connection string code here "
You have not open connection string so
add myconn.open()
for
SqlConnection myConn="must add your connection string code here "
`myconn.open()`
SqlDataAdapter sqlDa = new SqlDataAdapter(strQuery,myConn)
Try this..
ddlList.DataSource = sqlTa;
ddlList.DataTextField = "class";
ddlList.DataBind();
adding ddList.Value="somefield" is optional

Calling the functionfrom one class to another in a default datatable

I have a function like this in one of my classes and then I need to call it in another class and get the value in a default datatable.
public DataTable GetPrimaryKeyTables(string localServer, string userName, string password, string selectedDatabase)
{
// Create the datatable
DataTable dtListOfPrimaryKeyTables = new DataTable("tableNames");
SqlConnectionStringBuilder objConnectionString = new SqlConnectionStringBuilder();
objConnectionString.DataSource = localServer; ;
objConnectionString.UserID = userName;
objConnectionString.Password = password;
objConnectionString.InitialCatalog = selectedDatabase;
// Query to select primary key tables.
string selectPrimaryKeyTables = #"SELECT
TABLE_NAME
AS
TABLES
FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE
CONSTRAINT_TYPE = 'PRIMARY KEY'
ORDER BY
TABLE_NAME";
// put your SqlConnection and SqlCommand into using blocks!
using(SqlConnection sConnection = new SqlConnection(objConnectionString.ConnectionString))
using(SqlCommand sCommand = new SqlCommand(selectPrimaryKeyTables, sConnection))
{
try
{
// Create the dataadapter object
SqlDataAdapter sDataAdapter = new SqlDataAdapter(selectPrimaryKeyTables, sConnection);
// Fill the datatable - no need to open the connection, the SqlDataAdapter will do that all by itself
// (and also close it again after it is done)
sDataAdapter.Fill(dtListOfPrimaryKeyTables);
dgResultView.DataSource = dtListOfPrimaryKeyTables;
}
catch(Exception ex)
{
//All the exceptions are handled and written in the EventLog.
EventLog log = new EventLog("Application");
log.Source = "MFDBAnalyser";
log.WriteEntry(ex.Message);
}
}
// return the data table to the caller
return dtListOfPrimaryKeyTables;
}
Can anyone help me in this, every time I try, the controls are not inherited from one class to another.
I am not sure what you mean by 'controls not inherited from one class to another'.
you will create an object of this class in your another class and call the method on it.
something like this
class class1
{
public DataTable GetPrimaryKeyTables(string localServer, string userName, string password, string selectedDatabase)
.......
........
return dtListOfPrimaryKeyTables;
}
class Class2
{
protected void BindControl(....)
{
DataTable dt = new class1().GetPrimaryKeyTables(......);
dgResultView.DataSource = dt;
dgResultView.DataBind();
}
}
Either you pass 'dgResultView' as a parameter to the method or you use the above code snippet. Controls are defined as 'Protected', hence they won't be accessible in the other class. dgResultView.DataSource = dtListOfPrimaryKeyTables; used in the function is not gonna work.
It is a good idea to have your connection string and other information in a config file and is accessed from there.

How to count the number of rows and display it

I am working on a desktop application that returns list of tables that have foreign keys in a datagrid by this function.
public void GetPrimaryKeyTable()
{
//An instance of the connection string is created to manage the contents of the connection string.
var sqlConnection = new SqlConnectionStringBuilder();
sqlConnection.DataSource = "192.168.10.3";
sqlConnection.UserID = "gp";
sqlConnection.Password = "gp";
sqlConnection.InitialCatalog = Convert.ToString(cmbDatabases.SelectedValue);
string connectionString = sqlConnection.ConnectionString;
SqlConnection sConnection = new SqlConnection(connectionString);
//To Open the connection.
sConnection.Open();
//Query to select the table_names that have PRIMARY_KEYS.
string selectPrimaryKeys = #"SELECT
TABLE_NAME
FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE
CONSTRAINT_TYPE = 'PRIMARY KEY'
AND
TABLE_NAME <> 'dtProperties'
ORDER BY
TABLE_NAME";
//Create the command object
SqlCommand sCommand = new SqlCommand(selectPrimaryKeys, sConnection);
try
{
//Create the dataset
DataSet dsListOfPrimaryKeys = new DataSet("INFORMATION_SCHEMA.TABLE_CONSTRAINTS");
//Create the dataadapter object
SqlDataAdapter sDataAdapter = new SqlDataAdapter(selectPrimaryKeys, sConnection);
//Provides the master mapping between the sourcr table and system.data.datatable
sDataAdapter.TableMappings.Add("Table", "INFORMATION_SCHEMA.TABLE_CONSTRAINTS");
//Fill the dataset
sDataAdapter.Fill(dsListOfPrimaryKeys);
//Bind the result combobox with primary key tables
DataViewManager dvmListOfPrimaryKeys = dsListOfPrimaryKeys.DefaultViewManager;
dgResultView.DataSource = dsListOfPrimaryKeys.Tables["INFORMATION_SCHEMA.TABLE_CONSTRAINTS"];
}
catch(Exception ex)
{
//All the exceptions are handled and written in the EventLog.
EventLog log = new EventLog("Application");
log.Source = "MFDBAnalyser";
log.WriteEntry(ex.Message);
}
finally
{
//If connection is not closed then close the connection
if(sConnection.State != ConnectionState.Closed)
{
sConnection.Dispose();
}
}
}
Now I want to count the number of tables that fall in this category and display it in a lablel that this much of tables are under this category..
Can you guys please help me
I believe you can just use the DataSet.Tables.Count method.
http://msdn.microsoft.com/en-us/library/system.data.internaldatacollectionbase.count.aspx
Or, DataSet.Tables[i].Rows.Count

Binding data to a rich textbox control i windows application

Hi All,
I am currently binding my data in a datagrid like this
public DataTable GetAllPrimaryKeyTables(string localServer, string userName, string password, string selectedDatabase)
{
// Create the datatable
DataTable dtListOfPrimaryKeyTables = new DataTable("tableNames");
SqlConnectionStringBuilder objConnectionString = new SqlConnectionStringBuilder();
objConnectionString.DataSource = localServer; ;
objConnectionString.UserID = userName;
objConnectionString.Password = password;
objConnectionString.InitialCatalog = selectedDatabase;
// Query to select primary key tables.
string selectPrimaryKeyTables = #"SELECT
TABLE_NAME
AS
TABLES
FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE
CONSTRAINT_TYPE = 'PRIMARY KEY'
AND
TABLE_NAME <> 'dtProperties'
ORDER BY
TABLE_NAME";
// put your SqlConnection and SqlCommand into using blocks!
using(SqlConnection sConnection = new SqlConnection(objConnectionString.ConnectionString))
using(SqlCommand sCommand = new SqlCommand(selectPrimaryKeyTables, sConnection))
{
try
{
// Create the dataadapter object
SqlDataAdapter sDataAdapter = new SqlDataAdapter(selectPrimaryKeyTables, sConnection);
// Fill the datatable - no need to open the connection, the SqlDataAdapter will do that all by itself
// (and also close it again after it is done)
sDataAdapter.Fill(dtListOfPrimaryKeyTables);
}
catch(Exception ex)
{
//All the exceptions are handled and written in the EventLog.
EventLog log = new EventLog("Application");
log.Source = "MFDBAnalyser";
log.WriteEntry(ex.Message);
}
}
// return the data table to the caller
return dtListOfPrimaryKeyTables;
}
And then giving the datasource as this
protected void GetPrimaryKeyTables()
{
DataTable dtPrimaryKeys = new DataAccessMaster().GetAllPrimaryKeyTables(txtHost.Text, txtUsername.Text, txtPassword.Text, Convert.ToString(cmbDatabases.SelectedValue));
dgResultView.DataSource = dtPrimaryKeys;
}
But now I need to bind the datatable to a richtextbox control available in the toolbox.
Waiting for reply!!!
How to do that??
I don't think you can bind a dataTable to a RichTextBox "as is" because the structure of the two elements are intrinsically different. you can't "magically" bind a multi-element table to a single element string-containing element. IMHO you should extract the string from DB and put it into (or bind it as a string) your RichTextBox Control.

Categories