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.
Related
I Want to create a function in ClassProducts.cs file and when I call that function it should return Values & Tags for that ComboBox.
ComboBox Control is in ViewProducts Form and function in ClassProducts.cs class. Function accepts 1 parameter called Cat_ID
class ClassProducts
{
public DataTable FillSubCats(int catID)
{
DataTable items = new DataTable();
SqlCommand cmdFillSubCatL1 = new SqlCommand("SELECT * FROM tblProductCategories WHERE Cat_ParentCat =" + catID, con);
con.Open();
SqlDataReader sda = cmdFillSubCatL1.ExecuteReader();
while (sda.Read())
{
ComboboxItem item = new ComboboxItem();
item.Text = (sda["Cat_Name"]).ToString();
item.Value = (sda["Cat_ID"]).ToString();
items.Load(sda);
}
sda.Dispose();
sda.Close();
con.Close();
return items;
}
}
I want a function in ClassProducts file which will be filling ComboBoxes in ViewProducts.cs Form. Whenever function called it should return combo box items to the calling file.
I have tried this function but it is not working.
Please help.
Thank You.
This is most probably due to the fact that you are not using sqlparameters. Cat_ParentCat must be an int field so when you try to use query with string concatenation, a cats to nvarchar field is taking place, and since you don't wrap catId with quotes on your query, it fails . In any case using SQL Parameters, will also help you avoid SQL injection. Try:
SqlCommand cmdFillSubCatL1 = new SqlCommand("SELECT * FROM tblProductCategories WHERE Cat_ParentCat =#catId", con);
cmdFillSubCatL1.Parameteres.Add("#catId",SqlDbType.Int).Value=catId;
...
EDIT:
After Correct comment, a better query should be:
"SELECT Cat_Name,Cat_ID FROM tblProductCategories WHERE Cat_ParentCat =#catId"
Finally since you want to load a DataTable don't use Datareader but a dataAdapter:
...
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = cmdFillSubCatL1 ;
adapter.Fill(items );
How about this. I have added a method FillSubCatsProxy which should simulate what your method is returning.:
public Form1()
{
InitializeComponent();
comboBox1.DataSource = FillSubCatsProxy(1);
comboBox1.DisplayMember = "Cat_Name";
comboBox1.ValueMember = "Cat_ID";
comboBox1.SelectedIndexChanged += (s, e) => { MessageBox.Show("Selected:" + comboBox1.SelectedValue); };
}
public DataTable FillSubCatsProxy(int catID)
{
var dt = new DataTable();
dt.Columns.Add("Cat_Name");
dt.Columns.Add("Cat_ID");
dt.Rows.Add("Fish","1");
dt.Rows.Add("Jack","2");
return dt;
}
public DataTable FillSubCats(int catID)
{
SqlConnection con = new SqlConnection("Somewhere");
try
{
con.Open();
DataTable items = new DataTable();
var da = new SqlDataAdapter("SELECT Cat_Name,Cat_ID FROM tblProductCategories WHERE Cat_ParentCat = " + catID, con);
da.Fill(items);
return items;
}
finally
{
con.Close();
}
}
}
I would really appreciate a help in this code. I have a DataSet with two tables; I need to create a relation based on two columns as primary key:
public DataSet GetAll()
{
string sql = $#"SELECT * FROM Journal ORDER BY JvNO, cYear;
SELECT * FROM JournalDetail ORDER BY JvNO, cYear";
using (SqlConnection connection = new SqlConnection(GlobalConfig.ConnString()))
{
connection.Open();
SqlCommand cmd = new SqlCommand(sql, connection);
SqlDataAdapter da = new SqlDataAdapter(sql, connection);
DataSet ds = new DataSet();
da.Fill(ds);
ds.Relations.Add("Journal_Batch", new DataColumn[] { ds.Tables[0].Columns["JvNO"], ds.Tables[0].Columns["cYear"] },
new DataColumn[] { ds.Tables[1].Columns["JvNO"], ds.Tables[1].Columns["cYear"] });
return ds;
}
}
Currently, I'm doing it like this and it's working but I need it with DataSet relation:
public DataSet GetJournalByID(int JVNO, int cYear)
{
string sql = $#"SELECT * FROM Journal WHERE JvNO = { JVNO } and cYear = { cYear };
SELECT * FROM JournalDetail WHERE JvNO = { JVNO } and cYear = { cYear };";
using (SqlConnection connection = new SqlConnection(GlobalConfig.ConnString()))
{
connection.Open();
SqlCommand cmd = new SqlCommand(sql, connection);
SqlDataAdapter da = new SqlDataAdapter(sql, connection);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
}
I don't know what's wrong with first code, as it returns all matching JvNO or Year.
i want to use the first one to fill two grids as follow:
private void GetData()
{
DataSet currentDs = new DataSet();
grdJournalDetails.DataSource = null;
grdJournal.DataSource = null;
JournalConnector journalConnection = new JournalConnector();
currentDs = journalConnection.GetAll();
grdJournal.DataSource = currentDs.Tables[0];
grdJournalDetails.DataSource = currentDs.Tables[1];
}
then with each row selected from grdJournal to display grdJournalDetails with related data without calling each time the second snippet of code.
i used Dapper and i'm familiar with it, but with devexpress grid, it have to be a datatable to use the event gvJournal_FocusedRowChanged, otherwise datarow returns always null;
Thanks for any suggestion.
I have fetched the data from SQL server to datagridview but I don't know how to change the cell value. I have to change the fetched value 1 and 0 to available and unavailable. here is my code for fetching data ... please help.
private void btnsearch_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("server = 192.168.100.6;Database=sms;UID=sa;Password=1234;");
SqlCommand cmd = new SqlCommand("Select id as 'Book ID',name as 'Name' , status as 'Status' from book where Name = #name", con);
cmd.Parameters.AddWithValue("#name", txtFirstName.Text);
try
{
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
BindingSource bsource = new BindingSource();
bsource.DataSource = dt;
dataGridView1.DataSource = bsource;
}
catch (Exception ec)
{
MessageBox.Show(ec.Message);
}
// chage_value();
dataGridView1.Show();
}
}
Please find below answer
private void btnsearch_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("server = 192.168.100.6;Database=sms;UID=sa;Password=1234;");
string sSql=#"Select id as 'Book ID',name as 'Name' ,
Case when status=0 then 'unavailable' else 'available '
End as 'Status' from
book where Name ='"+txtFirstName.Text +"'"
SqlCommand cmd = new SqlCommand(sSql, con);
try
{
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
catch (Exception ec)
{
MessageBox.Show(ec.Message);
}
// chage_value();
dataGridView1.Show();
}
}
First of all, try to store your queries in variables. This will help you in the long run. Also, it is good practise to check whether you are connected or not before trying to send a query away to the server. It is important to remeber that when you fetch data from your server, it will most likely be seen as a string, so if you want to compare it as a number, you need to convert it first.
What you could do is something similar to what i've written below. You count the amount of answers your query returns, then loop through them and check whether they are 0 or 1. Then just replace the value with Avaliable or Unavaliable.
if (dbCon.IsConnect()){
MySqlCommand idCmd = new MySqlCommand("Select * from " + da.DataGridView1.Text, dbCon.Connection);
using (MySqlDataReader reader = idCmd.ExecuteReader()){
// List<string> stringArray = new List<string>(); // you could use this string array to compare them, if you like this approach more.
while (reader.Read()){
var checkStatus= reader["Status"].ToString();
Console.WriteLine("Status: " + checkStatus.Split(' ').Count()); //checks how many items you've got.
foreach (var item in checkStatus.Split(' ').Select(x => x.Trim()).Where(x => !string.IsNullOrWhiteSpace(x)).ToArray()){
var item2 = 0.0; // your 0 or 1 for avaliable or unavaliable..
try{
item2 = double.Parse(item.ToString());
if(strcmp(item2,'0') == 1){ //assuming you only have 0's and 1's.
item2 = "unavaliable";
}else{
item2 = "avaliable";
}
}
catch (Exception){
//do what you want
}
Console.WriteLine("item: " + item2);
}
}
dbCon.Close();
}
}
return //what you want;
}
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";
i have large number of rows in my database. when i tried to load all the data in to datagridview it getting stuck. i want to load data to datagridview that only related datetimepicker date. this is my current code
private void showdatagrid()
{
string constring = string.Format("datasource='{0}';username=uwadminview;port=3306;password=*****************;Connect Timeout=20000;Command Timeout=28800", dbserverip.Text);
MySqlConnection conwaqDatabase = new MySqlConnection(constring);
MySqlCommand cmdwaqDatabase = new MySqlCommand(" select * from waq115.loans ; ", conwaqDatabase);
try
{
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmdwaqDatabase;
dbdataset = new DataTable();
sda.Fill(dbdataset);
BindingSource bsource = new BindingSource();
bsource.DataSource = dbdataset;
dataGridView1.DataSource = bsource;
sda.Update(dbdataset);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
conwaqDatabase.Close();
}
then soon after i call this i again use a rowfilter event like this
private void filterdata()
{
DataView DV = new DataView(dbdataset);
DV.RowFilter = string.Format("Convert(submittimestamp, System.String) LIKE '%{0}%'", adminviewDTP.Text);
dataGridView1.DataSource = DV;
}
but in this method performance is very bad when loading more than 9000 rows it getting stuck all the time. i want to method that directly query data from database only related to today
(users are daily update the database and they are insert more than 500 rows each day)
(application still in a testing progress)
(i'm using mysql database)
can someone show me any efficient way to do this)
MySqlCommand cmdwaqDatabase = new MySqlCommand("SELECT * FROM waq115.loans WHERE DATE(submittimestamp) = DATE(NOW())", conwaqDatabase);
UPDATE:
With parameter:
MySqlCommand cmdwaqDatabase = new MySqlCommand("SELECT * FROM waq115.loans WHERE DATE(submittimestamp) = DATE(#p)", conwaqDatabase);
then you can add the parameter like below
cmdwaqDatabase.Parameters.AddWithValue("#P", dateTimeValue); // convert datetime picker value to DateTime and set as the value;
or
cmdwaqDatabase.Parameters.Add(new MySqlParameter("#P", MySqlDbType.Timestamp)).Value = dateTimeValue;
Filter in the database tier instead of the middle tier.
MySqlConnection conwaqDatabase = new MySqlConnection(constring);
MySqlCommand cmdwaqDatabase =
new MySqlCommand("select * from waq115.loans where submittimestamp = #date; ", conwaqDatabase);
var dateParam = new MySqlParameter();
dateParam.Name = "#date";
dateParam.Value = Convert.ToDateTime(adminviewDTP.Text);
cmdwaqDatabase.Parameters.Add(dateParam);