Modified Data Table - c#

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.

Related

display data to listbox C#

Listbox does not show data. Verified data is in database and I am not getting an
error. Not sure where/what is wrong. Thanks in advance. My code is attached.
private void UpDateList()
{
// add data connection and fill data set.
SqlConnection conn = new SqlConnection(dataSource);
DataTable dt = new DataTable();
string sqlString = "select * from Suppliers";
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
cmd.Connection = conn;
conn.Open();
cmd.CommandText = sqlString;
da.Fill(ds);
conn.Close();
}
catch (SqlException ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
conn.Close();
}
foreach(DataRow dRow in ds.Tables[0].Rows)
{
ArrayList values = new ArrayList();
foreach(object value in dRow.ItemArray)
{
values.Add(value);
_Suppliers.Add(values);
}
}
lstSuppliers.DataSource = _Suppliers;
lstSuppliers.Update();
}
It's kinda pointless to enumerate one bindable data collection and transfer data into another bindable collection so it can be bound. Just have your list use the default view of the datatable that already holds the data (allows sorting, filtering etc)
E.g.
LstSuppliers.DataSource = ds.Tables[0].DefaultView;
LstSuppliers.DisplayMember = "column name goes here of what to show eg SupplierName";
LstSuppliers.ValueMember = "column whose value to use for lstSuppliers.SelectedValue e.g. supplierId";
And then for example, not required but an example possibility:
ds.Tables[0].DefaultView.Sort = "[SupplierName] ASC";

Getting value from last row of SQL Server database C#

public queue getQueueDataByID(int queueID)
{
string DBConnect = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
SqlDataAdapter da;
DataSet ds = new DataSet();
queue myQueue = new queue();
StringBuilder sqlCommand = new StringBuilder();
sqlCommand.AppendLine("Select * from QueueTable where");
sqlCommand.AppendLine("id = #paraId");
try
{
SqlConnection myConn = new SqlConnection(DBConnect);
// sqlCommand.Parameters.AddWithValue("paraCustId", tbCustId.Text);
da = new SqlDataAdapter(sqlCommand.ToString(), myConn);
da.SelectCommand.Parameters.AddWithValue("paraId", queueID);
// fill dataset
da.Fill(ds, "QueueTable");
//conn.Close();
int rec_cnt = ds.Tables["QueueTable"].Rows.Count;
DataRow row = ds.Tables["QueueTable"].Rows[rec_cnt-1 ];
myQueue.queueNo = row["QueueNo"].ToString();
myQueue.NRIC = row["NRIC"].ToString();
myQueue.ContactNo = row["ContactNo"].ToString();
}
catch (SqlException ex)
{
}
return myQueue;
}
This is my class,I am trying to retrieve the datas from the last row of the database to display in a web form, any idea how i can do that? My "id", primary key is set as autoincrement.
You can use Linq on the datatable to get the last row.
var queueDataTable = ds.Tables[0];
var lastDataRow = queueDataTable.AsEnumerable().Last();
If you need to itterate through all the rows in the datatable
foreach (var dataRow in queueDataTable.AsEnumerable())
{
}
thanks

How to get datarow column values by using c#

Iam using a datatable to fetch table values from mysql DB.
My codes
public static DataTable mydealdetails()
{
try
{
string connString = "Server=localhost;database=mytable;uid=root;password=Mytable";
string query = "SELECT * FROM `mytable`.`mydealdetails`";
MySqlDataAdapter ma = new MySqlDataAdapter(query, connString);
DataSet DS = new DataSet();
ma.Fill(DS);
return DS.Tables[0];
}
catch (MySqlException e)
{
throw new Exception(e.Message);
}
}
And iam also using this methode
var expression = "MovieMasterId = '"+mouvieid+"'";
DataRow[] foundRows = allmydeals.Select(expression);
I can get two rows count here,but i want to know how can i get each column values by using this methode

retrieve with multi or

im creating wfp application i want to retrieve table to datagridview
with multi value selected in listbox, getting all data that selected from listbox, so the main idea
is apply this query from sql to application
select * from Vwtb where firstname='' or firstaname='' or ..
i have tried with while loop and searched a lot but not worked this is my code please if its something strange for you im not professional :)
string[] orand = { "or"+listBox1.Text };
foreach (string sm in orand)
{
cn.Open();
string select = "select * from productvw where firstname='" + sm + "'";
SqlDataAdapter dataAdapter = new SqlDataAdapter(select, cn);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataTable ds = new DataTable();
dataAdapter.Fill(ds);
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = ds;
cn.Close();
}
any type of help will be so appreciated ....
You can convert your array to a string that can be used in IN operator.for achieving that, use this extension method
public static class StaticClass
{
public static string ConvertStringArrayToString(this string[] array)
{
StringBuilder builder = new StringBuilder();
for (int i=0;i<array.Length;i++)
{
builder.Append(array[i]);
if(i+1==array.Length)break;
builder.Append(',');
}
return builder.ToString();
}
}
Then in your code use it like this
string[] orand = { "or"+listBox1.Text };
var values=orand.ConvertStringArrayToString();
cn.Open();
string select =" SELECT * FROM productvw WHERE firstname IN "+"("+values+")"
SqlDataAdapter dataAdapter = new SqlDataAdapter(select, cn);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataTable ds = new DataTable();
dataAdapter.Fill(ds);
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = ds;
cn.Close();
You could use the IN operator.
string command = "SELECT * FROM productvw WHERE firstname IN (#names)";
SqlDataAdapter dataAdapter = new SqlDataAdapter(select, cn);
dataAdapter.Parameters.Add("#names", names);
The names would be a list of strings, List<string>, and would contain all the first names you want to use.
You can use the following syntax:
SELECT *
FROM productvw
WHERE firstname IN (value1,value2,...);
Start by creating a loop that generates the sql string With the values populated.

Select from dataset where data in dataset matches user input

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() + "' ");

Categories