Select from dataset where data in dataset matches user input - c#

I am trying to query or match user input against a dataset using a DataTable:
I am populating the dataset from a stored procedure which selects only a single column from a single table: Example: UserID Column. **I am not selecting the entire content of the table.*
public static DataSet LoadProfile()
{
SqlCommand cmdSQL = new SqlCommand("usp_LoadProfile", ConnectDatabase);
cmdSQL.CommandType = CommandType.StoredProcedure;
SqlDataAdapter daSQL = new SqlDataAdapter(cmdSQL);
DataSet ds = new DataSet();
daSQL.Fill(ds);
try
{
ConnectDatabase.Open();
cmdSQL.ExecuteNonQuery();
}
catch(Exception)
{
StatusMsg = ex.Message;
}
finally
{
ConnectDatabase.Close();
cmdSQL.Parameters.Clear();
cmdSQL.Dispose();
}
return ds;
}
I have the following method called in the form load event: I need to populate the dataset on from load.
public static DataTable LoadData()
{
DataSet dsView = new DataSet();
dsView = LoadProfile();
DataTable tblExample = dsView.Tables["Example"];
return tblExample;
}
Finally what I would like to do is match the user entry from the DataTable.
I have this in button event:
DataRow[] results;
results = LoadData().Select(txtExample.Text);
Beyond this point, I could use a for loop but there is only one record for each person.
I am trying to match the user entry with the dataset via the datatable.

The last line should be
DataRow[] results;
results = LoadData().Select("UserID = '" + txtExample.Text +"'");
Supposing that UserID is a field of text type. If instead is of numeric type then remove the quotes
results = LoadData().Select("UserID = " + txtExample.Text);
However I should point that the code in LoadProfile following the daSQL.Fill(ds); call is not needed and you can remove it (just return the DataSet though)

Use the following simple query on dataset:
DataRow[] dRow = dataSetName.Tables[0].Select("fieldToMatch = '" + userInput.ToString() + "' ");

Related

how to populate combo box from database and insert new item on index zero in C#

This code below works for me, but i have not been able to insert ---Select--- to the for first index with value zero, i have tried:
cboGrade.Items.Insert(0,"---Select---)
but it is not working for me.
Also i want to able to retrieve and display the displaymember and displayvalue on the combo box while retrieving from database without items not being repeated:
private void LoadGrade()
{
using (SQLiteConnection conn = new SQLiteConnection(connstring))
{
try
{
string query = "select GradeCode, GradeName from Grade";
SQLiteDataAdapter da = new SQLiteDataAdapter(query, conn);
conn.Open();
DataSet ds = new DataSet();
da.Fill(ds, "OrgGrade");
cboGrade.DisplayMember = "GradeName";
cboGrade.ValueMember = "GradeCode";
cboGrade.DataSource = ds.Tables["OrgGrade"];
}
catch (Exception ex)
{
MessageBox.Show("Error occured loading grade!");
}
}
}
Items only works if you have an unbound combo hence you either need to build the items array OR use binding.
What you need to do is insert into the DataTable you are binding like this:
DataTable dt = ds.Tables["OrgGrade"]
// generate the data you want to insert
DataRow newRow= dt.NewRow();
newRow.GradeName = "-- Select --";
newRow.GradeCode = 0;
// insert in the desired place
dt.Rows.InsertAt(newRow, 0);
Then bind using:
cboGrade.DataSource = dt;
Similar to what you have.

how to collect multiple dataset data into one dataset?

I need to show multiple records together in a gridview in c# with SQL.
i have an array of Id's using those id's i need to get all details correspond to those id's.
i have an array ID[] Dataset ds
for(int i=0; i<=ID.Length-1; i++)
{
dss = fill_DS("select Client_id, F_name, L_name, Ph, Alt_ph, Time_date, Plan_duration, Brand, Email from Client_detail where Client_id='" + ID[i]+ "'");
}
Second method
public static DataSet fill_DS(string query)
{
DataSet ds=null;
try
{
SqlDataAdapter da = new SqlDataAdapter(query, con);
ds = new DataSet();
da.Fill(ds);
}
catch (Exception ex)
{
}
return ds;
}
It only returns me the result of the last row only or for last id only. i need to combine the rows for all id's and show them in a gridview.
How to do this?

Modified Data Table

For example I have this table
EmployeeName EmpoyeeID
John Mark 60001
Bent Ting 60002
Don Park 60003
How I can show the EmployeeID to have a leading asterisk in data table?
Sample: *60001 *60002 *60003
public DataTable ListOfEmployee()
{
DataSet ds = null;
SqlDataAdapter adapter;
try
{
using (SqlConnection myDatabaseConnection = new SqlConnection(myConnectionString.ConnectionString))
{
myDatabaseConnection.Open();
using (SqlCommand mySqlCommand = new SqlCommand("Select * Employee", myDatabaseConnection))
{
ds = new DataSet();
adapter = new SqlDataAdapter(mySqlCommand);
adapter.Fill(ds, "Users");
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return ds.Tables[0];
}
I need to show the dataTable in the crystal report with a leading asterisk in the employee ID
public void Employees()
{
ReportDocument rptDoc = new ReportDocument();
Employees ds = new Employees(); // .xsd file name
DataTable dt = new DataTable();
// Just set the name of data table
dt.TableName = "Employees";
dt = ListOfEmployee(); //This function is located below this function
ds.Tables[0].Merge(dt);
string strReportName = "Employees.rpt";
string strPath = Application.StartupPath + "\\Reports\\" + strReportName;
// Your .rpt file path will be below
rptDoc.Load(strPath);
//set dataset to the report viewer.
rptDoc.SetDataSource(ds);
ReportViewer newReportViewer = new ReportViewer();
newReportViewer.setReport(rptDoc);
newReportViewer.Show();
}
the easiest not the best way to do is to get the data in that format, if and only if it is not meant to be used anywhere else. You can do this in your query
Select '*'+id,col1,col2,col3 from employee
Though the best way is to modify the column value when you consume it. But obviously that is more headache than adding simply in the query.
Add it into the Crystal report itself.
Something like -
"*" & {tblTable.FieldName}
(Although I can't remember the syntax for Crystal reports, sorry!)
Not tested, but replacing the return statement at the end of your function with the following code should work:
DataTable table = ds.Tables[0];
DataTable clonedTable = table.Clone();
clonedTable.Columns["EmployeeID"].DataType = typeof(String);
foreach (DataRow row in table.Rows)
{
clonedTable.ImportRow(row);
}
foreach (DataRow row in clonedTable.Rows)
{
row["EmployeeID"] = "*" + row["EmployeeID"].ToString();
}
return clonedTable;
However, as others have said, I would recommend adding the asterick somewhere down the line when the data is read rather than to the table itself.

store select result

i want to extract my table names and save it into variables this is my cod that return 3 answer:student, teacher and score. how can i change it to save these tree table name to 3 variable. thank you.
try
{
SqlDataReader myreader = null;
SqlCommand mycommand = new SqlCommand("select * FROM information_schema.tables WHERE table_type = 'BASE TABLE'", myconnect);
myreader = mycommand.ExecuteReader();
while (myreader.Read())
{
Console.WriteLine(myreader[2].ToString());
}
}
A simple builtin way is using Connection.GetSchema:
using (var con = new System.Data.SqlClient.SqlConnection(conStr))
{
con.Open();
DataTable schemaTable = con.GetSchema("Tables");
IList<string> allTableNames = schemaTable.AsEnumerable()
.Where(r => r.Field<string>("TABLE_TYPE") == "BASE TABLE")
.Select(r => r.Field<string>("TABLE_NAME"))
.ToList();
}
Now you have a List<string> with all table names which you can access via indexer or in a loop or create a comma separated list with string.Join:
string tNames = string.Join(",", allTableNames);
Console.Write("all tables in the given database: " + tNames);
You can use this :
string tableName ="" ; // Variable to stroe the table names
string connectionString = ""; //Your connectionstring
// get records from the table
string commandString =""; //Your query
// create the data set command object
// and the DataSet
SqlDataAdapter DataAdapter =new SqlDataAdapter(commandString, connectionString);
DataSet DataSet = new DataSet( );
// fill the DataSet object
DataAdapter.Fill(DataSet, "Customers");
// Get the one table from the DataSet
DataTable dataTable = DataSet.Tables[0];
// for each row in the table, display the info
foreach (DataRow dataRow in dataTable.Rows)
{
tableName = dataRow[0].tostring();
//...
}
if you want to save the result for future user or a different session then you can use any of the following to methods
first one
use the "insert" query to save the result one by one in the a different table that you would create specially for saving the data
you can put the insert command/statement directly into the for loop
second method
use the xml to store the value very simple and memory friendly
I Have modified #Doctor code to use ArrayList to store number of table name in single variables.
ArrayList alTableName = new ArrayList(); // Variable to stroe the table names
string connectionString = ""; //Your connectionstring
// get records from the table
string commandString =""; //Your query
// create the data set command object
// and the DataSet
SqlDataAdapter DataAdapter =new SqlDataAdapter(commandString, connectionString);
DataSet DataSet = new DataSet( );
// fill the DataSet object
DataAdapter.Fill(DataSet, "Customers");
// Get the one table from the DataSet
DataTable dataTable = DataSet.Tables[0];
// for each row in the table, display the info
foreach (DataRow dataRow in dataTable.Rows)
{
alTableName.Add(dataRow[0].tostring());
//...
}

can we assign objectdatasource control to a dataset?

I have two questions:
Can we assign objectdatasource control to a dataset?
Can we return two or more tables using object data source control to gridview or detailsview.
My main focus is I have to store the object data source in the dataset otherwise my application will need to be changed by a lot.
1 Yes you can assign objectdatasource to a DataSet
private DataSet GetDataSet(ObjectDataSource ods)
{
var ds = new DataSet();
var dv = (DataView)ods.Select();
if (dv != null && dv.Count > 0)
{
var dt = dv.ToTable();
ds.Tables.Add(dt);
}
return ds;
}
2 yes you can return lot of tables, but when you bind you specify your index table.
GridView1.DataSource = YourDataSet.Tables[0];
GridView2.DataSource = YourDataSet.Tables[2];
An 'ObjectDataSource' has no data.
He simply returns the result of a method, this method should return an IEnumerable. The IEnumerable can be of POCO's, String's, Int32's, etc..
how to store a objectdatasource controls data into a dataset
It would be possible if you return a "System.Data.DataTable" and then, yes, in this case you could store it in a "System.Data.DataSet". But for me, it makes little sense.
private void Form5_Load(object sender, EventArgs e)
{
// Creating and configuring the ObjectDataSource component:
var objectDataSource = new Telerik.Reporting.ObjectDataSource();
objectDataSource.DataSource = GetAllData(); // GetData returns a DataSet with three tables
objectDataSource.DataMember = "Product"; /// Indicating the exact table to bind to. If the DataMember is not specified the first data table will be used.
objectDataSource.CalculatedFields.Add(new Telerik.Reporting.CalculatedField("FullName", typeof(string), "=Fields.Name + ' ' + Fields.ProductNumber")); // Adding a sample calculated field.
// Creating a new report
Telerik.Reporting.Report report = new Telerik.Reporting.Report();
// Assigning the ObjectDataSource component to the DataSource property of the report.
report.DataSource = objectDataSource;
// Use the InstanceReportSource to pass the report to the viewer for displaying
Telerik.Reporting.InstanceReportSource reportSource = new Telerik.Reporting.InstanceReportSource();
reportSource.ReportDocument = report;
// Assigning the report to the report viewer.
reportViewer1.ReportSource = reportSource;
// Calling the RefreshReport method (only in WinForms applications).
reportViewer1.RefreshReport();
}
static DataSet GetAllData()
{
const string connectionString =
"Data Source=(local)\\SQLEXPRESS;Initial Catalog=AdventureWorks;Integrated Security=True";
string selectCommandText = "SELECT Name, ProductCategoryID FROM Production.ProductCategory;" +
"SELECT Name, ProductCategoryID FROM Production.ProductSubcategory;" +
"SELECT Name, ProductNumber FROM Production.Product;";
SqlDataAdapter adapter = new SqlDataAdapter(selectCommandText, connectionString);
DataSet dataSet = new DataSet();
// The data set will be filled with three tables: ProductCategory, ProductSubcategory
// and Product as the select command contains three SELECT statements.
adapter.Fill(dataSet);
// Giving meaningful names for the tables so that we can use them later.
dataSet.Tables[0].TableName = "ProductCategory";
dataSet.Tables[1].TableName = "ProductSubcategory";
dataSet.Tables[2].TableName = "Product";
return dataSet;
}

Categories