How to get datarow column values by using c# - 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

Related

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 add an extra Item in ComboBox using c#

Currently i'm populating a combobox with items from a database.However, i want the first item of combobox to be "---Select---".I am using the following code.All the items from database are getting populated but not the item "---Select---". Any help in this regard is highly appreciated.
private void popClass()
{
cmbClass.Items.Clear();
DataSet ds = new DataSet();
cmbClass.Items.Add("---Select----");
string sqlPS = #"SELECT * FROM tblclass_msb";
try
{
using (FbConnection conPS = new FbConnection(connectionString))
{
conPS.Open();
using (FbCommand cmdPS = new FbCommand(sqlPS, conPS))
{
using (FbDataAdapter da = new FbDataAdapter())
{
da.SelectCommand = cmdPS;
da.Fill(ds);
cmbClass.DataSource = ds.Tables[0];
cmbClass.ValueMember = "c_id";
cmbClass.DisplayMember = "c_name";
}
}
}
}
catch (FbException ex)
{
MessageBox.Show("PC-->>" + ex.Message);
}
}
i have tried other solutions mentioned somewhere in the other threads but its not working for me
you have to add new row at zero position you an do it like this:
private void popClass()
{
cmbClass.Items.Clear();
DataSet ds = new DataSet();
cmbClass.Items.Add("---Select----");
string sqlPS = #"SELECT * FROM tblclass_msb";
try
{
using (FbConnection conPS = new FbConnection(connectionString))
{
conPS.Open();
using (FbCommand cmdPS = new FbCommand(sqlPS, conPS))
{
using (FbDataAdapter da = new FbDataAdapter())
{
da.SelectCommand = cmdPS;
da.Fill(ds);
DataRow dr=ds.Tables[0].NewRow();
dr["c_id"]=0;
dr["c_name"]="--Select--";
ds.Tables[0].Rows.InsertAt( dr,0);
cmbClass.DataSource = ds.Tables[0];
cmbClass.ValueMember = "c_id";
cmbClass.DisplayMember = "c_name";
}
}
}
}
catch (FbException ex)
{
MessageBox.Show("PC-->>" + ex.Message);
}
}
If you were connecting to SQL Server using SqlCommand, you could simply change the SQL statement to the following:
string sqlPS = #"select 0 as c_id, '--Select--' as c_name union SELECT c_id, c_name FROM tblclass_msb";
However, it looks like you're connecting to Firebird and I can't be sure if union is supported.

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

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.

Bind duplicate rows in Dataset once

I am merging two datasets and I wish that duplicate rows are only bind once ,how can I achieve this ?
protected void RadGrid1_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
{
showRelatedcat();
DataSet ds = new DataSet();
DataSet ds_frd = new DataSet();
String frdQuery = my query
String newquery = my other query
String queryString = another one
try
{
// Connect to the database and run the query.
SqlConnection connection = new SqlConnection(connectionString);
SqlDataAdapter adapter = new SqlDataAdapter(newquery, connection);
SqlDataAdapter adapter1 = new SqlDataAdapter(frdQuery, connection);
// Fill the DataSet.
adapter1.Fill(ds_frd);
adapter.Fill(ds);
ds.Merge(ds_frd, true);
connection.Close();
}
catch (Exception ex)
{
// The connection failed. Display an error message.
//Message.Text = "Unable to connect to the database.";
}
RadGrid1.DataSource = ds.Tables[0].;
}
both queries have some rows as common .
you can merge dataset using Dataset.Merge using IEnumerable function
http://social.msdn.microsoft.com/Forums/en-US/csharplanguage/thread/ebe7e4c2-2cad-4a9d-9134-2732d1e05664
it allows you to get only one value in duplicate case

Categories