SQL IN operator in asp.net C# - c#

I am getting an error while binding a gridview. I want to select multiple records from database using SQL IN operator. Please help me to overcome this problem.
aspx.cs code
string codeId = "4,3,5,7";
int[] result = codeId.Split(',').Select(int.Parse).ToArray();
string Qry = "select CodeId,Code,AccountHead,Rate from AccountHeads Where CodeId IN " + result; //Getting error here
SqlDataAdapter adp = new SqlDataAdapter(Qry, con);
DataTable dt = new DataTable();
adp.Fill(dt);
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.EmptyDataText = "no records founds";
GridView1.DataBind();
//Hide Gridview columns
GridView1.Columns[0].Visible = false;
}

You don't need to split your string with , and use IEnumerable.Select to select int values.
You already have a nicely formatted string for IN clause. You just need to use your values in () like;
string Qry = string.Format(#"select CodeId,Code,AccountHead,Rate
from AccountHeads Where CodeId IN ({0})",
codeId);

Related

SQL Query not Retrieving All Rows in C# Application

I have a stored procedure created in my SQL Server 2012 database that selects data from multiple tables. In C#, I use this procedure to show data in a datagridview.
Issue: when I execute the query in SQL Server, I get the correct result which returns 3 rows, but in C#, it returns only 2 rows.
Query:
SELECT DISTINCT
Employee.Employee_No AS 'Badge'
,Employee.Employee_Name_Ar AS 'Emp Name'
,Employee.Basic_Salary AS 'Basic'
,Employee.Current_Salary AS 'Current'
,Attendance.Present
,Attendance.Leave
,Attendance.Othe_Leave AS 'OL'
,Pay_Slip.Salary_Amount AS 'Sal. Amt.'
,(ISNULL(Pay_Slip.OverTime1_Amount, 0.00) + ISNULL(Pay_Slip.OverTime2_Amount, 0.00)) AS 'O/T Amt.'
,(ISNULL(Pay_Slip.Salary_Amount, 0.00) + ISNULL(ISNULL(Pay_Slip.OverTime1_Amount, 0.00) + ISNULL(Pay_Slip.OverTime2_Amount, 0.00), 0.00)) AS 'Sal. & O/T'
,Pay_Slip.Trasnport AS 'Allow'
,Pay_Slip.CostofLiving AS 'O.Allow'
,Pay_Slip.Gross_Salary AS 'T Salary'
,Pay_Slip.Insurance1_Amount AS 'ss 7%'
,Pay_Slip.Insurance2_Amount AS 'ss 11%'
,(ISNULL(Pay_Slip.Insurance1_Amount, 0.00) + ISNULL(Pay_Slip.Insurance2_Amount, 0.00)) AS 'Total s.s'
,Pay_Slip.Tax
,Pay_Slip.Personal_Loans AS 'Advance'
,Pay_Slip.Other_Deductions AS 'Ded.'
,Pay_Slip.Net_Salary AS 'Net'
FROM Pay_Slip
LEFT JOIN Employee ON Pay_Slip.Employee_No = Employee.Employee_No
LEFT JOIN Attendance ON Pay_Slip.Employee_No = Attendance.Employee_No
WHERE Pay_Slip.Month = '5'
AND Pay_Slip.Year = '2020'
AND Attendance.Month = '5'
AND Attendance.Year = '2020'
Executing this query in SQL Server returns 3 rows which are the employee slips on May-2020 (They all have values in May-2020).
C# code:
private void dateTimePicker_ReportDate_ValueChanged(object sender, EventArgs e)
{
try
{
DateTime date = dateTimePicker_ReportDate.Value;
String Month = dateTimePicker_ReportDate.Value.ToString("MM");
String Year = dateTimePicker_ReportDate.Value.ToString("yyyy");
String str = "server=localhost;database=EasyManagementSystem;User Id=Jaz;Password=Jaz#2020;Integrated Security=True;";
String query = "Execute EMP_PAY_ATT_Selection #Month, #Year";
SqlConnection con = null;
con = new SqlConnection(str);
SqlCommand cmd= new SqlCommand(query, con);
cmd.Parameters.Add("#Month", SqlDbType.Int).Value = Convert.ToInt32(Month);
cmd.Parameters.Add("#Year", SqlDbType.Int).Value = Convert.ToInt32(Year);
SqlDataReader sdr;
con.Open();
sdr = cmd.ExecuteReader();
if (sdr.Read())
{
DataTable dt = new DataTable();
dt.Load(sdr);
dataGridView_Report.DataSource = dt;
dataGridView_Report.EnableHeadersVisualStyles = false;
dataGridView_Report.ColumnHeadersDefaultCellStyle.BackColor = Color.LightBlue;
}
else
{
dataGridView_Report.DataSource = null;
dataGridView_Report.Rows.Clear();
}
con.Close();
}
catch (Exception es)
{
MessageBox.Show(es.Message);
}
}
Again, when running this, it only returns 2 rows on the datagridview. While it should be 3 rows.
These are the tables:
The DbDataReader.Read method advances the reader to the next record.
There is no way to rewind a data reader. Any methods that you pass it to will have to use it from whatever record it is currently on.
If you want to pass the reader to DataTable.Load(), do not Read from it yourself. If you merely want to know if it contains records, use HasRows.

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 datatable with join return 0

I have one DataTable that executes this SQL query on my MS Access database in C#:
DataTable dtCdDvd = cls.Fun_RetornaDataTable("SELECT tblCdDvd.Cod, tblCdDvd.Nome, tblCdDvd.Tamanho, tblTipo.Tipo, tblCdDvd.Grupo FROM [tblCdDvd] INNER JOIN [tblTipo] ON tblCdDvd.Tipo=tblTipo.Cod WHERE Status = TRUE");
If I use
DataRow[] result = dtCdDvd.Select("[Grupo]=0");
the result is 0 rows and exist registry with informed code.
The more interesting is if my SQL query runs
DataTable dtCdDvd = cls.Fun_RetornaDataTable("SELECT Grupo FROM tblCdDvd");
without join table my result is different of 0.
My function of return datatable
public DataTable Fun_RetornaDataTable(string query)
{
DataTable dt = null;
using (var dbcon = new OleDbConnection(Fun_ConnString()))
{
dbcon.Open();
if (dbcon.State == ConnectionState.Open)
{
var command = new OleDbCommand(query, dbcon);
dt = new DataTable();
dt.Load(command.ExecuteReader());
}
}
return dt;
}
Very difficult to understand the question, but a couple of things that stand out.
" WHERE Status = TRUE"
What is 'Status'? Is it defined in one of the tables uniquely?
When you run "SELECT Grupo FROM tblCdDvd", are you getting any rows returned?
"the result is 0 rows and exist registry with informed code"
What does this mean in English?

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

problem with getting data from database

I am trying to get the data from database by using the below code.....
if there is no data in the table it will always goes to
this statement
I am using mysql.net connector for getting the data and i am doing winforms applications
using c#
public DataTable sales(DateTime startdate, DateTime enddate)
{
const string sql = #"SELECT memberAccTran_Source as Category, sum(memberAccTran_Value) as Value
FROM memberacctrans
WHERE memberAccTran_DateTime BETWEEN #startdate AND #enddate
GROUP BY memberAccTran_Source";
return sqlexecution(startdate, enddate, sql);
}
and the below code is for return sqlexceution...function..
private static DataTable sqlexecution(DateTime startdate, DateTime enddate, string sql)
{
var table = new DataTable();
using (var conn = new MySql.Data.MySqlClient.MySqlConnection(connectionstring))
{
conn.Open();
var cmd = new MySql.Data.MySqlClient.MySqlCommand(sql, conn);
var ds = new DataSet();
var parameter = new MySql.Data.MySqlClient.MySqlParameter("#startdate", MySql.Data.MySqlClient.MySqlDbType.DateTime);
parameter.Direction = ParameterDirection.Input;
parameter.Value = startdate.ToString(dateformat);
cmd.Parameters.Add(parameter);
var parameter2 = new MySql.Data.MySqlClient.MySqlParameter("#enddate", MySql.Data.MySqlClient.MySqlDbType.DateTime);
parameter2.Direction = ParameterDirection.Input;
parameter2.Value = enddate.ToString(dateformat);
cmd.Parameters.Add(parameter2);
var da = new MySql.Data.MySqlClient.MySqlDataAdapter(cmd);
da.Fill(ds);
try
{
table = ds.Tables[0];
}
catch
{
table = null;
}
}
return table;
}
even if there is no data the process flow will goes to this line
table = ds.Tables[0];
how can i reduce this .....
would any one pls help on this....
In your case if you are think that catch block will get excuted if there is no row available than you are wrong because Even if there is no data once select query is get exucuted without exception it Creates datatable with the columns but with no rows.
for this i think you can make use of ds.table[0].rows.count property which return 0 if there is no row in datatable.
if ( ds.Tables[0].Rows.Count > 0 )
table = ds.Tables[0];
else
table=null;
It returns an empty table. This is common behavior. If you want to have table null you should check for the row count :
If ( ds.Tables[0].Rows.Count >. 0 )
table = ds.Tables[0];
Else
table=0
I'm not really sure what you're asking here ... I assume you want it to skip the table = ds.tables[0] line if there is no data?
if thats the case a try/catch wont work as it wont throw an exception ... try something like this instead ...
if(ds.Tables.Count > 0 && ds.Tables[0].Rows.Count >0)
{
table = ds.Tables[0];
}
else
{
table = null;
}

Categories