I have a several data column from my MySQL database, the type is tinyint(1)
my code in form
DataTable dt = new DataTable();
dt = PC.getValue(textBox.Text);
dataGridView1.DataSource = dt;
dataGridView1.AutoResizeColumns();
and MyQuery
public DataTable getValue(string yearmonth)
{
connSIMRS.Open();
MySqlCommand command = new MySqlCommand();
string sql = "select * from table1 where yearmonth= '"+yearmonth+"'";
command.CommandText = sql;
command.Connection = connSIMRS;
//command.EndExecuteNonQuery();
MySqlDataAdapter da = new MySqlDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
//MessageBox.Show("");
connSIMRS.Close();
return dt;
}
can't post a picture but it turn into a checkbox. Could it be turn into a boolean? How can I show it as a string?
Yes, it is being turned into a boolean. Many ways to turn it into a string. Use a custom format, custom column, cast it from the database, etc.
Force MySql Connector to do it:
According to the MySQL Connector Docs , just add TreatTinyAsBoolean=false to your connection string.
However, I would just use a custom column in the GridView, as most cases I would want the booleans to be displayed as a checkbox, and this allows finer control over which ones I want displayed as text vs checkbox.
Add the obligitory string sql = "select * from table1 where yearmonth= '"+yearmonth+"'"; is bad. Don't do that EVER.
Related
I currently have a Drop down list that has been bound with dates from a database. The dates differ depending on which username is selected in a different drop down list. I am trying to populate a GridView depending on these values and when the selected index changes on the dates drop down list.
However the dates being displayed in my drop down list are dd/mm/yyyy 00:00:00, which means that I can't use them to display data from the database based on the values. As my Date in the database are stored as yyyy/mm/dd. As I am getting the error : 'Conversion failed when converting date and/or time from character string.'
Any idea on how to change the format in the drop down list?
I understand that this might be used: DateTime.ToString("yyyy-MM-dd"); however I can't work out where.
C# for binding data to my second drop down list:
private void BindDropDownList2(String field)
{
DataTable dataTable = new DataTable();
SqlConnection con = new SqlConnection(#"Data Source=(local)\;Initial Catalog=SmallBatch;Integrated Security=True;");
try
{
con.Open();
String Query = "Select StockDate from Stock_Take WHERE Username = #Value1";
SqlCommand sqlCmd = new SqlCommand(Query, con);
sqlCmd.Parameters.AddWithValue("#Value1", field);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
sqlDa.Fill(dataTable);
if (dataTable.Rows.Count > 0)
{
DropDownList2.DataSource = dataTable;
DropDownList2.DataTextField = "StockDate";
DropDownList2.DataValueField = "StockDate";
DropDownList2.DataBind();
}
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Fetch Error";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
con.Close();
}
}
Firstly , a DataTable is unnecessary here.Go with a IDataReader , it's a better option.The reason is simple.A DataTable uses a DataAdapter and stores data from the database.Which means you have 2 datatables,one in the database(original one) and one in the code behind.If you go with IDataReader it means that you are reading the data-table from the database itself and not storing it again in code-behind.
Ow, did i forget to tell that a DataReader is proven to be faster than a DataAdapter ? :).
I'l glad that you almost answered you own question with this line :
I understand that this might be used: DateTime.ToString("yyyy-MM-dd")
All you have to do is put it all together :
SqlCommand sqlCmd = new SqlCommand(Query, con);
sqlCmd.Parameters.AddWithValue("#Value1", field);
SqlDataReader dr = sqlCmd.ExecuteReader();
While (dr.Read())
{
DropDownList1.Items.Add(new ListItem(dr[0].ToString("yyyy MMM ddd"), ""));
} //I didn't debug this line but it should work :)
Update
As OP said that the data-type of the given column is VarChar, then .ToString() will do it :)
DropDownList1.Items.Add(new ListItem(dr[0].ToString()),"");
I am trying to populate a datagrid table and add an additional combobox in a Winforms application to allow the user to select from an exception list.
The datagrid is populated using a Stored Procedure on SQL server.
(NOTE: due to my ITs security I have to go through a single server using linked servers to where the data is to query the data so the stored procedure uses dynamic SQL)
The data pulls properly and the additional combobox appears however once I select an exception on 1 row and try to go to the next row, the first combobox's selection disappears.
An additional question, given the nature or how I query the data, how would I update the data on the original sql tables from datagrid? Another stored procedure?
FYI, I'm a SQL developer but I'm fairly new to C#
My code is below for the datagridview method. Thanks in advance.
public void displayDataGridView(string param)
{
SqlConnection con = new SqlConnection("Data Source = SQLServer1; initial catalog=GlbDBNames; integrated security=true ");
{
SqlCommand cmd;
cmd = new SqlCommand(param, con);
cmd.CommandTimeout = 60 * 20;
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
dg_batchsummary.DataSource = ds.Tables[0];
dg_batchsummary.Columns[0].Width = 200;
dg_batchsummary.AutoGenerateColumns = false;
dg_batchsummary.AllowUserToAddRows = false;
DataGridViewComboBoxColumn ExceptionList = new DataGridViewComboBoxColumn();
ExcptionList.HeaderText = "Exception List";
ExceptionList.Name = "Newexcept";
ExceptionList.Items.AddRange("Item1","Item2","Item3");
dg_batchsummary.Columns.Add(ExceptionList);
}
Possible that I'm overlooking something here, but when I load a DataTable from SqlCommand.ExecuteReader() I am finding that the MaxLength property of my String field is ignored and reset to '50' in the resulting DataColumn. Here's an example table:
CREATE TABLE MySqlServerTable (
[instance_id] INT NOT NULL,
[field_id] INT NOT NULL,
[value] VARCHAR (MAX) NOT NULL);
and the method I'm using to initialize the local DataTable is
public DataTable GetDT()
{
string query = "SELECT top 0 * FROM MySqlServerTable;";
SqlCommand cmd = new SqlCommand(query, _msSqlConn);
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
return dt;
}
where _msSqlConn is the already opened SqlConnection. If I then scroll through the DataColumns, I find that the value column (the string column) has been assigned a MaxLength of 50.
Console.WriteLine(GetDT().Columns["value"].MaxLength);
So what gives?
Kinda related to this attempted answer but still unresolved.
What's the right way to do this such that my string column MaxLengths are properly retrieved from the SqlServer2012 DB?
I think you need to use DataAdapter.FillSchema() to retrieve meta data. Try this something like this:
_msSqlConn.Open();
using (SqlDataAdapter da = new SqlDataAdapter(query, _msSqlConn))
{
DataTable dt = new DataTable();
da.FillSchema(dt, SchemaType.Mapped); //Or may be SchemaType.Source
return dt;
}
Basically what I want is the fill query of the data grid view like this
SELECT DealerName, OrderId, DealerId, OrderDate, ItemType, Price, Quantity, Total, TotalBill FROM dbo.DetailedRecord where DealerName=ComboboxName.SelectedValue
I can't see how to add parameters to it and I don't want to use the fill by toolstrip
Thanks
Why not use a stored procedure, then give it a dataset to fill it with your information?
Populate DataGridView from a Stored Procedure
Let's say you want to filter the data by some combobox.selectedvalue and you have a submit button, in that submit button code,you initialize a new datatable of the type yourdatasource.table like
YourDataSource.YourTableDataTable anything= new YourDataSource.YourTableDataTable();
yourdataadapter.fill(anything,parametervalue.tostring());
DataGridView1.datasource= anything;
And you're all set.
Try binding the table to your DataGridView.
See below for a simple example:
MySqlConnection conn = new MySqlConnection(connectionstring);
conn.Open();
string stmt = "SELECT DealerName, OrderId, DealerId, OrderDate, ItemType, Price, Quantity,
Total, TotalBill FROM dbo.DetailedRecord where DealerName=ComboboxName.SelectedValue";
DataSet ds = new DataSet();
MySqlDataAdapter da = new MySqlDataAdapter(stmt, conn);
da.Fill(ds, "dbo.DetailedRecord");
dataGridView1.DataSource = ds.Tables["dbo.DetailedRecord"];
conn.Close();
Simply pass your parameters as a string into your query. Use simple string concatenation (++). Watch how you create that search string carefully. Ensure that you initialize the DataTable first or else it will spring an error about null parameters: For example (Works on SQL Server , Mysql and Postgres)
String connectionString = "server = ...; db= ...; passwd = ....;";
DataTable dt_reservation_product_mix = new DataTable();
MySqlDataAdapter ad3;
ad3 = new MySqlDataAdapter("select `product`.`name`, `product`.`notes` from `product` where `product`.`code` = " + Convert.ToString(ComboboxName.SelectedValue) + "; ", connectionString);
ad3.Fill(dt_reservation_product_mix);
ad3.Dispose();
Below is my Datagridview code to get the data from employee table.
the problem am facing is ,my employee table have 10 columns (ID,emplNo,Dob,JoingData...etc)
i just want to fill my grid with only ID,EmplyNo and DOB.
but the below code get everything,please advise me what i suppose to do to get only particular column
string sql = "select * from Employee";
SqlConnection connection = new SqlConnection(CONNECTION_STRING);
//SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
dataadapter = new SqlDataAdapter(sql, connection);
// DataSet ds = new DataSet();
ds = new DataSet();
connection.Open();
dataadapter.Fill(ds, scrollVal, 5, "Employee");
connection.Close();
dgMessages.DataSource = ds;
dgMessages.DataMember = "tEmployee";
instead of
string sql = "select * from Employee";
do
string sql = "select ID, EmplyNo, DOB from Employee";
either change your select to only get the supset of what you want or use the designer:
it's a bit of a pain because you first have to add an unbound column and then edit the just added column to setthe DataPropertyName to a column-name in your resulting table - but it works.
You find this dialogs by clicking the "..." in the "columns" property of the PropertyEditor for the DataGridView or by clicking the little "Play"-Button on the top-right of the Grid in the designer (when it is selected)
Almost forgot: IMPORTANT: you need to add EVERY column and set Visible=False on those you don't want to see - I think this is different in WebForms where there is something like AutogenerateColumns.