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.
Related
I created a Windows Forms application in C# and my database in Visual Studio. I want to know how, if it's possible, to sort one of the columns in the table by clicking a button? Or how can I sort this column automatically without using a button?
I've tried to implement this sort in the code below, but it doesn't work :(
private c void button5_Click(object sender, EventArgs e)
{
SqlConnection sqlConnection = new SqlConnection("Here is my connecting string");
SqlCommand myCommand = new SqlCommand("SELECT * FROM [Information] ORDER BY (Перевозчик)", sqlConnection);
sqlConnection.Open();
myCommand.ExecuteNonQuery();
}
As found here: https://www.w3schools.com/sql/sql_orderby.asp
Sine we don't know what you want to oder we can only guess here.
But with the query you could try:
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC
In your case:
"SELECT * FROM [Information] ORDER BY (Перевозчик) ASC"
Best would be to use the visual query builder where you can query against your database. When you are happy with your result you can at least be sure that the query is correct.
How you can do that is explained here:
https://www.c-sharpcorner.com/article/connect-to-a-database-from-visual-studio/
Since the sqlconnection and the sqlcommand is disposable you should consider putting it in a using tag, like in this example.
https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand?view=netframework-4.8
private static void ReadOrderData(string connectionString)
{
string queryString =
"SELECT OrderID, CustomerID FROM dbo.Orders;";
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(
queryString, connection);
connection.Open();
using(SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
}
}
}
There is 2 way for sort data
1) sorting just data and fill into grid:
DataGridView datagridview1 = new DataGridView(); // for show data
DataTable dt1 = new DataTable(); // have data
DataTable dt2 = new DataTable(); // temp data table
DataRow[] dra = dt1.Select("", "ID DESC");
if (dra.Length > 0)
dt2 = dra.CopyToDataTable();
datagridview1.DataSource = dt2;
2) sort default view that is like of sort with grid column header:
DataGridView datagridview1 = new DataGridView(); // for show data
DataTable dt1 = new DataTable(); // have data
dt1.DefaultView.Sort = "ID DESC";
datagridview1.DataSource = dt1;
I found this solution here:
Sorting rows in a data table
For a listbox you could give this a shot
ArrayList q = new ArrayList();
foreach (object o in listBox4.Items)
q.Add(o);
}
q.Sort();
listBox5.Items.Clear();
foreach(object o in q){
listBox5.Items.Add(o);
}
I found this solution here:
Sorting a list of items in a list box
You need to do ExecuteDatareader then process the result coming from this call. ExecuteNonQuery cannot be used to retrieve data.
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.
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.
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
I have defined the function in one class like
public static DataSet GetAllPrimaryKeyTables()
{
//An instance of the connection string is created to manage the contents of the connection string.
using(var sConnection = new SqlConnection(ConfigurationSettings.AppSettings["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
using(var sCommand = new SqlCommand(selectPrimaryKeys, sConnection))
{
try
{
//Create the dataset.
DataSet dsPrimaryKeyTables = new DataSet("INFORMATION_SCHEMA.TABLE_CONSTRAINTS ");
//Create the dataadapter object.
SqlDataAdapter daPrimaryKeyTables = new SqlDataAdapter(selectPrimaryKeys, sConnection);
//Provides the master mapping between the sourcr table and system.data.datatable
daPrimaryKeyTables.TableMappings.Add("Table", "INFORMATION_SCHEMA.TABLE_CONSTRAINTS ");
//Fill the dataadapter.
daPrimaryKeyTables.Fill(dsPrimaryKeyTables);
//Bind the result combobox with non primary key table names
DataViewManager dsvPrimaryKeyTables = dsPrimaryKeyTables.DefaultViewManager;
return dsPrimaryKeyTables;
}
catch(Exception ex)
{
//Handles the exception and log that to the EventLog with the original message.
EventLog log = new EventLog("Application");
log.Source = "MFDBAnalyser";
log.WriteEntry(ex.Message);
return null;
}
finally
{
//checks whether the connection is still open.
if(sConnection.State != ConnectionState.Closed)
{
sConnection.Close();
}
}
}
}
}
And now how should i code so that I can call that function in another class in a dafault dataset.
Will anybody please help me??
Making this function an Extension Method on DataSet type will sole your problem if I understand you,
You will use something like this.
Dataset myPrimaryKeyDataset = YourClassName.GetAllPrimaryKeyTables();
Hope this helps.