I am new in net I want to use data table instead of a database.
I want to know that why is data table query different from an sql query?
I want to find a value from data table:
SELECT dbo.General_Ledger.Entry_Amount FROM dbo.General_Ledger WHERE Account_number=lbDebit_Account_numer
and
using (SqlConnection connect = new SqlConnection(con))
{
int index = lbDebit_Account.FindString(txtDebit_Account.Text);
if (0 <= index)
{
lbDebit_Account.SelectedIndex = index;
}
SqlDataAdapter da3 = new SqlDataAdapter("SELECT *FROM dbo.General_Ledger", connect);
DataTable dt1 = new DataTable();
da3.Fill(dt1);
string lbDebit_Account_numer = lbDebit_Account.SelectedValue.ToString();
string row;
row= Convert.ToString(dt1.Select(string.Format("'Account_number'={0}",lbDebit_Account_numer)));
}
I want to perform this query:
SELECT dbo.General_Ledger.Entry_Amount FROM dbo.General_Ledger WHERE Account_number=lbDebit_Account_numer
So you'll want to parameterize your query:
SqlDataAdapter da3 = new SqlDataAdapter("SELECT * FROM dbo.General_Ledger WHERE Account_number = #Account_number");
da3.SelectCommand.Parameters.AddWithValue("#Account_number", lbDebit_Account.SelectedValue);
DataTable dt1 = new DataTable();
da3.Fill(dt1);
and now you'll have just the one row you want and you can recover it like this:
DataRow dr = dt1.Rows[0];
and then you can grab values off of that row a number of different ways:
var val = dr[0]; // grabs the value of the first column in the result list
var val = dr["fieldname"] // grabs the value of a specific field name
and there are even some methods that will returned typed data because the aforementioned return an object since the underlying value could be a number of things. So, if it were a string field you were after you could do something like:
var val = dr.Field<string>(0) // grabs the value of the first column and returns it typed as a string
var val = dr.Field<string>("fieldname") // grabs a field and returns it typed as a string
It very simple, u want to filter the DataTable[dt1] base on this string[lbDebit_Account_numer]
DataRow dr = dt1.Select("Account_number = '"+lbDebit_Account_numer ="'");
u can use
AND OR
operators
single code['] need for string variables to compare.
here u get data-row, all cell will in an array format you select any cell.
You can try to use DefaultView.RowFilter property of DataTable class.
Example:
dataTable.DefaultView.RowFilter = "Account_number=1";
Related
EX In "Data" table
type of column from moisture to end is Boolean
I want to get column name has data is "1" to combobox
Specifically, for each row of my result set, I need a collection of those column names which contain the value 1 so I can populate a combobox.
Sorry for my English I'm not good enough.
pic "Data" table
Using the MySQL .net connector (and any RDMS connector) when you are reading a result set from a query, you will have a DataReader object. In MySQL's case it is a MySqlDataReader.
For example (from https://dev.mysql.com/doc/connector-net/en/connector-net-tutorials-sql-command.html)
string sql = "SELECT * FROM data";
MySqlCommand cmd = new MySqlCommand(sql, conn);
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
/* iterate once per row */
Console.WriteLine(rdr[0]+" -- "+rdr[1]); /* or whatever */
}
rdr.Close();
Once you have a valid DataReader, you can use the GetSchemaTable() method to obtain a DataTable collection of data describing the result set. This information comes from MySQL as part of the result set. For example:
MySqlDataReader rdr = cmd.ExecuteReader();
DataTable schema = rdr.GetSchemaTable();
This DataTable contains a row for each column in the result set. You can access useful information about your columns in your result set like this:
foreach (DataRow rdrColumn in schema.Rows) {
String columnName = rdrColumn[schema.Columns["ColumnName"]].ToString();
String dataType = rdrColumn[schema.Columns["DataType"]].ToString();
}
There are also items named ColumnSize, NumericPrecision, NumericScale, and so forth. Each of these is available for each column in the result set if you need them.
Edit
You can make a Dictionary holding the names of the result set's columns like this:
Dictionary<int,String> columnNames = new Dictionary<int,string>();
int index = 0;
foreach (DataRow row in schema.Rows) {
columnNames.Add(index,row[schema.Columns["ColumnName"]].ToString());
index++;
}
Thereafter, as you iterate through the rows, you can create a List of columns, by name, with a certain row value.
while (rdr.Read()) {
/* for each row */
List<String> listOfColumns = new List<string>();
for (int i = 0; i < rdr.FieldCount; i++) {
var val = rdr[i];
if ("1" == val) {
/* if the value of the column is 1, add the column name from the dictionary */
listOfColumns.Add(columnNames[i]);
}
}
}
For examples of looking at result set metadata see here. https://etutorials.org/Programming/ado+net/Part+I+ADO.NET+Tutorial/Chapter+5.+DataReaders/5.4+DataReaders+and+Schema+Information/
this query will help you DESCRIBE my_table;
SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'my_database' AND TABLE_NAME = 'my_table';
refer the clink for more clarification: https://dev.mysql.com/doc/refman/8.0/en/show-columns.html
I need to know what the size parameter should be for a DateTime value using the following syntax:
adapter.InsertCommand.Parameters.Add("#deliveryDateAndTime", SqlDbType.DateTime,10,"deliveryDateAndTime");
I cannot use the following syntax because I'm batching the updates in a datatable.
adapter.InsertCommand.Parameters.Add("#deliveryDateAndTime", SqlDbType.DateTime);
adapter.InsertCommand.Parameters["#deliveryDateAndTime"] = *variable*.value;
Below is the code I need to use (abbreviated for clarity). Note that inside the adapter.InsertCommand.Parameters.Add("#deliveryDateAndTime", SqlDbType.DateTime,10,"deliveryDateAndTime"); statement, the first parameter refers to a corresponding SQL parameter and the 4th parameter corresponds to the data for that value inside the datatable.
DataTable dt = new DataTable();
foreach (FuelDelivery fd in fuelDelivery.FuelDeliveries)
{
DataRow dr = dt.NewRow();
dr["deliveryDateAndTime"] = fd.DeliveryDateAndTime;
dt.Rows.Add(dr);
}
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["HHSqlConnection"].ToString()))
{
// Create a SqlDataAdapter.
SqlDataAdapter adapter = new SqlDataAdapter();
// Set the INSERT command and parameter.
adapter.InsertCommand.Parameters.Add("#deliveryDateAndTime", SqlDbType.DateTime,10,"deliveryDateAndTime");
adapter.InsertCommand.UpdatedRowSource = UpdateRowSource.None;
// Set the batch size. Zero represents the maximum amt of rows to update at once.
adapter.UpdateBatchSize = 0;
// Execute the update.
int rowsUpdated = adapter.Update(dt);
}
Based on this overload for the adapter.InsertCommand.Parameters.Add method, how can I set the date accordingly?
A datetime is 8 bytes according to the easily searchable documentation.
Note that you could also use your preferred overload and set the source column separately:
adapter.InsertCommand.Parameters.Add("#deliveryDateAndTime", SqlDbType.DateTime)
.SourceColumn = "deliveryDateAndTime";
I have an application,which is not able to fetch data from the database for this specific form, while other forms are working fine.
I am using this form to fetch data from database and then display that data onto labels on an another form.
The code for fetching data is:
string PName, DName, Psex, PPhoneNo, PAddress, Treatment, Teethno, PAge, Amount;
SqlDataAdapter a = new SqlDataAdapter("Select bills.BillNo,bills.PName,bills.DName,bills.PAge,bills.PSex,bills.PPhoneNo,bills.PAddress,bills.Treatment,bills.Amount,bills.Teethno,addpro.Medicines from bills,addpro where bills.BillNo=" + bno, Program.con);
DataTable t = new DataTable();
a.Fill(t);
PAge = Convert.ToString(t.Rows[3]);
Amount = Convert.ToString(t.Rows[8]);
PName = Convert.ToString(t.Rows[1]);
DName = Convert.ToString(t.Rows[2]);
Psex = Convert.ToString(t.Rows[4]);
PPhoneNo = Convert.ToString(t.Rows[5]);
PAddress = Convert.ToString(t.Rows[6]);
Treatment = Convert.ToString(t.Rows[7]);
Teethno = Convert.ToString(t.Rows[9]);
frmPrint sa=new frmPrint();
sa.start(bno, PAge, Amount, PName, DName, Psex, PPhoneNo, PAddress, Treatment, Teethno);
when i try to load the next form which displays the data from this DataTable on labels it gives the following error:-
There is no row at position 3.
Your're using Row and you want to be using Column:
foreach(DataRow row in t.Rows)
{
PAge = row["PAge"].ToString();
Amount = row["Amount"].ToString();
PName = row["PName"].ToString();
DName = row["DName"].ToString();
Psex = row["PSex"].ToString();
PPhoneNo = row["PPhoneNo"].ToString();
PAddress = row["PAddress"].ToString();
Treatment = row["Treatment"].ToString();
Teethno = row["Teethno"].ToString();
}
Instead of using the number to identify the column, use the name. If the order of the query was to change for any reason, this would not have an impact on your code. If you used the Ordinal number, then you would need to change your row[n] code too since the order would have changed.
You are accessing different rows for each field.
You should access the first row and then different columns:
t.Rows[0].Columns[0]
t.Rows[0].Columns[1]
t.Rows[0].Columns[2]
t.Rows[0].Columns[3]
...
Seems like you need to use [Columns]
DataTable t = new DataTable();
a.Fill(t);
PAge = Convert.ToString(t.Rows[0]["ColumnsName"]);
// and so on
I have the following method created and previously stock1Label to stock3Label were able to output the correct values from the database however after i added more rows to my ProductsTable, source.Rows[0][0], [1][0], etc. seems to be taking values from row 8 onwards of my table instead of row 1, anyone know why this is happening?
private void UpdateStocks()
{
string query = "SELECT pQty FROM ProductsTable";
OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, DBconn);
DataTable source = new DataTable();
dAdapter.Fill(source);
stock1Label.Text = source.Rows[0][0].ToString();
stock2Label.Text = source.Rows[1][0].ToString();
stock3Label.Text = source.Rows[2][0].ToString();
stock4Label.Text = source.Rows[3][0].ToString();
stock5Label.Text = source.Rows[4][0].ToString();
stock6Label.Text = source.Rows[5][0].ToString();
}
Most (all?) database systems do not have defined orders.
You will receive rows in non-determinstic storage order, not in the order you inserted them.
To receive a meaningful consistent ordering, you need to add an ORDER BY clause.
I have a postgresql db and a C# application to access it. I'm having a strange error with values I return from a NpgsqlDataAdapter.Fill command into a DataSet.
I've got this code:
NpgsqlCommand n = new NpgsqlCommand();
n.Connection = connector; // a class member NpgsqlConnection
DataSet ds = new DataSet();
DataTable dt = new DataTable();
// DBTablesRef are just constants declared for
// the db table names and columns
ArrayList cols = new ArrayList();
cols.Add(DBTablesRef.all); //all is just *
ArrayList idCol = new ArrayList();
idCol.Add(DBTablesRef.revIssID);
ArrayList idVal = new ArrayList();
idVal.Add(idNum); // a function parameter
// Select builder and Where builder are just small
// functions that return an sql statement based
// on the parameters. n is passed to the where
// builder because the builder uses named
// parameters and sets them in the NpgsqlCommand
// passed in
String select = SelectBuilder(DBTablesRef.revTableName, cols) +
WhereBuilder(n,idCol, idVal);
n.CommandText = select;
try
{
NpgsqlDataAdapter da = new NpgsqlDataAdapter(n);
ds.Reset();
// filling DataSet with result from NpgsqlDataAdapter
da.Fill(ds);
// C# DataSet takes multiple tables, but only the first is used here
dt = ds.Tables[0];
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
So my problem is this: the above code works perfectly, just like I want it to. However, if instead of doing a select on all (*) if I try to name individual columns to return from the query I get the information I asked for, but rather than being split up into seperate entries in the data table I get a string in the first index of the data table that looked something like:
"(0,5,false,Bob Smith,7)"
And the data is correct, I would be expecting 0, then 5, then a boolean, then some text etc. But I would (obviously) prefer it to not be returned as just one big string.
Anyone know why if I do a select on * I get a datatable as expected, but if I do a select on specific columns I get a data table with one entry that is the string of the values I'm asking for?
Ok, I figured it out, it was in the SelectBuilder function. When more than one column was listed in the select statement it was wrapping the columns in ()'s, and apparently this causes either postgreSQL or Npgsql to interpret that as a desire to return a list in string form.