2 DataGridViews with same result? - c#

need some help with a simple code
This is for Visual Studio c# Win Forms
dgvScad.DataSource =
dataProvider.getAttestatiByScad(DateTime.Today.AddDays(dayScad),
DateTime.Today);
dgvProve.DataSource =
dataProvider.getAziendaliByScad(DateTime.Today.AddDays(dayScad),
DateTime.Today);
a
public DataTable getAttestatiByScad(DateTime scadenza1, DateTime scadenza2)
{
string sql = "SELECT CONCAT(Dipendenti.cognome, ' ', Dipendenti.nome) AS Nome, Attestati.nome AS Attestato, AssAttestati.scadenza AS Scadenza " +
" FROM Attestati INNER JOIN(AssAttestati INNER JOIN Dipendenti" +
" ON AssAttestati.matricola=Dipendenti.matricola) " +
" ON Attestati.ID=AssAttestati.attestato " +
" WHERE AssAttestati.scadenza<=#scadenza1 AND AssAttestati.scadenza>=#scadenza2;";
DataTable dt = db.EseguiQueryWithParams
(
sql,
new SqlParameter("#scadenza1", scadenza1),
new SqlParameter("#scadenza2", scadenza2)
);
return dt;
}
public DataTable getAziendaliByScad(DateTime scadenza1, DateTime scadenza2)
{
string sql = "SELECT Aziendali.nome, Aziendali.scadenza FROM Aziendali WHERE Aziendali.scadenza<=#scadenza1 AND Aziendali.scadenza>=#scadenza2";
DataTable dt = db.EseguiQueryWithParams
(
sql,
new SqlParameter("#scadenza1", scadenza1),
new SqlParameter("#scadenza2", scadenza2)
);
return dt;
}
public DataTable EseguiQueryWithParams(string sql, params SqlParameter[] parameters)
{
apriConnessione();
string nometab = "dump";
cmd.CommandText = sql;
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.AddRange(parameters);
try
{
adp = new SqlDataAdapter(cmd);
if (dset.Tables[nometab] != null)
dset.Tables[nometab].Clear();
adp.Fill(dset, nometab);
DataTable d = dset.Tables[nometab];
//d.Columns;
return d;
}
catch (Exception e)
{
throw e;
//throw new System.Exception("Errore nella lettura della tabella");
}
finally
{
adp.Dispose();
cmd.Dispose();
ChiudiConnessione();
}
}
I excpect the output to be different results, but all I see its the same for one DataGridView and the other DataGridView.
Hope you understand what I wronte I'm not so good in English.
It looks like your post is mostly code; please add some more details.
It looks like your post is mostly code; please add some more details.?

Related

DataTable returns "0" as value

I have a problem with getting data from sqlite database. Normally it works fine in other forms but on my last query all the returns "0".
try
{
using (SQLiteConnection baglanti = new SQLiteConnection(Uygulama.baglantiMetni))
{
if (baglanti.State != ConnectionState.Open)
baglanti.Open();
string sorgu = "SELECT tyOzellikDegerID, tyOzellikDegeri FROM tblTYKategoriOzellikDegerleri WHERE tyOzellikID=:ozellikkodu";
using (SQLiteDataAdapter da = new SQLiteDataAdapter(sorgu, baglanti))
{
da.SelectCommand.Parameters.AddWithValue(":ozellikkodu", Convert.ToInt32(kod));
DataTable dt = new DataTable();
da.Fill(dt);
cmbTYOzellikDegerleri.DisplayMember = "tyOzellikDegeri";
cmbTYOzellikDegerleri.ValueMember = "tyOzellikDegerID";
cmbTYOzellikDegerleri.DataSource = dt;
foreach(DataRow dr in dt.Rows)
{
Console.WriteLine(dr["tyOzellikDegeri"].ToString());
}
}
}
}
catch (Exception hata)
{
if (Uygulama.logTut == 1)
Fonksiyonlar.logYaz("FrmTeyStokListesi - ggOzellikDegeleri(" + kod + ") - " + hata.Message);
}
DataRow returns "0".
But if I run the code on sqlitedatabrowser it works fine.
I couldn't find the problem.

Between dates Oracle from c# using Oracle.dataaccess client

I have used the below query to access the data from Oracle all_objects view. When trying the same from Oracle SQL Developer it work fine and from C# code it is not fetching any data.
SELECT OBJECT_NAME,OBJECT_TYPE,CREATED,LAST_DDL_TIME
FROM sys.all_objects
where object_type='TABLE'
AND OWNER='SYS'
AND LAST_DDL_TIME between to_date('01/01/2013','DD/MM/YYYY')
and to_date('01/10/2016','DD/MM/YYYY')
If I use the below query without any filter it works fine in both Oracle and from C# as well...
SELECT OBJECT_NAME,OBJECT_TYPE,CREATED,LAST_DDL_TIME FROM sys.all_objects
Any idea that why it is not working?
Below are the sample value that is passed in the getDatSet function, Dates are select from c# DateTimepicker
strFromDate - {2/15/2012 12:00:00 AM}
strToDate - {11/15/2016 2:31:48 PM}
public DataSet GetDataSet(DateTime strFromDate, DateTime strToDate, List<string> strObjects)
{
OracleCommand objCmd;
OracleDataAdapter objDA;
DataSet objDS;
string StrSqlObjects = string.Empty; ;
try
{
StrSqlObjects += " SELECT OBJECT_NAME,OBJECT_TYPE,CREATED,LAST_DDL_TIME FROM sys.all_objects where ";
StrSqlObjects += " LAST_DDL_TIME between to_date(:startdate,'DD/MM/YYYY') and to_date(:enddate,'DD/MM/YYYY')";
objCmd = new OracleCommand(StrSqlObjects);
objCmd.Connection = m_Conn;
objCmd.Parameters.Clear();
objCmd.Parameters.Add("startdate", strFromDate);
objCmd.Parameters.Add("enddate",strToDate);
objDA = new OracleDataAdapter();
objDA.SelectCommand = objCmd;
var oracleCommandBindByNameProperty = objCmd.GetType().GetProperty("BindByName");
oracleCommandBindByNameProperty.SetValue(objCmd, true, null);
objDS = new DataSet();
objDS.Tables.Add("AllChange");
objDA.Fill(objDS, "Allchange");
}
catch (System.Exception e)
{
System.Diagnostics.Debug.WriteLine("Error GetDataSet " + e.Message);
throw e;
}
finally
{
CloseConnection();
}
return objDS;
}

Not getting any row data from database using c# asp.net.

I can not get any row data from database using c# asp.net.I am trying to fetch one row data from my DB but it is not returning any row.I am using 3-tire architecture for this and i am explaining my code below.
index.aspx.cs:
protected void userLogin_Click(object sender, EventArgs e)
{
if (loginemail.Text.Trim().Length > 0 && loginpass.Text.Trim().Length >= 6)
{
objUserBO.email_id = loginemail.Text.Trim();
objUserBO.password = loginpass.Text.Trim();
DataTable dt= objUserBL.getUserDetails(objUserBO);
Response.Write(dt.Rows.Count);
}
}
userBL.cs:
public DataTable getUserDetails(userBO objUserBO)
{
userDL objUserDL = new userDL();
try
{
DataTable dt = objUserDL.getUserDetails(objUserBO);
return dt;
}
catch (Exception e)
{
throw e;
}
}
userDL.cs:
public DataTable getUserDetails(userBO objUserBO)
{
SqlConnection con = new SqlConnection(CmVar.convar);
try
{
con.Open();
DataTable dt = new DataTable();
string sql = "SELECT * from T_User_Master WHERE User_Email_ID= ' " + objUserBO.email_id + "'";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataAdapter objadp = new SqlDataAdapter(cmd);
objadp.Fill(dt);
con.Close();
return dt;
}
catch(Exception e)
{
throw e;
}
}
When i am checking the output of Response.Write(dt.Rows.Count);,it is showing 0.So please help me to resolve this issue.
It looks like your your query string has a redundant space between ' and " mark. That might be causing all the trouble as your email gets space in front.
It is by all means better to add parameters to your query with use of SqlConnection.Parameters property.
string sql = "SELECT * from T_User_Master WHERE User_Email_ID=#userID";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.Add("#userID", SqlDbType.NVarChar);
cmd.Parameters["#userID"].Value = objUserBO.email_id;

Get the Row values from a excel based on the column Value

I am trying to a get the Row values from a excel sheet, based on the column Value.
e.g. I have CutsomerID as lets say 5 , so I want First name 5, last Name 5 and Address 5
I am converting whole excel sheet into DataTable and then trying to read on each DataRow, when I get CustomerID as 5, I copy all the values and break from the loop
Here is my code and it is working fine as well, but I was wondering is there any way to optimise it.
Here is my Code.
public ExcelData GetDataByCustomerID(String excelFilePath, String customerID)
{
OleDbConnectionStringBuilder connectionStringBuilder = new OleDbConnectionStringBuilder();
connectionStringBuilder.Provider = "Microsoft.ACE.OLEDB.12.0";
connectionStringBuilder.DataSource = excelFilePath;
connectionStringBuilder.Add("Mode", "Read");
const string extendedProperties = "Excel 12.0;IMEX=1;HDR=YES";
connectionStringBuilder.Add("Extended Properties", extendedProperties);
String connectionString = connectionStringBuilder.ToString();
// Create connection object by using the preceding connection string.
using( var objConn = new OleDbConnection(connectionString))
{
objConn.Open();
// Get the data table contaning the schema guid.
DataTable excelSheetsDataTable = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (excelSheetsDataTable == null)
return null;
// get all the tables in the Sheet
List<String> excelSheets = (from DataRow row in excelSheetsDataTable.Rows select row["TABLE_NAME"].ToString()).ToList();
// Our data is on First sheet only
OleDbCommand _oleCmdSelect = new OleDbCommand(#"SELECT * FROM [" + excelSheets[0] + "]", objConn);
OleDbDataAdapter oleAdapter = new OleDbDataAdapter();
oleAdapter.SelectCommand = _oleCmdSelect;
DataTable newDataTable = new DataTable();
oleAdapter.FillSchema(newDataTable, SchemaType.Source);
oleAdapter.Fill(newDataTable);
if (newDataTable.Columns.Contains("CustomerID"))
{
foreach (DataRow rowValue in newTB.Rows)
{
if ((string) rowValue["CustomerID"] == customerID)
{
var data = new ExcelData
{
customerFirstName = rowValue["Customer_First_ Name"].ToString(),
customerLastName = rowValue["Customer_Last_Name"].ToString(),
customerAddress = rowValue["Customer_Address"].ToString(),
};
return data;
}
}
String message = String.Format("The CustomerID {0} not found in Excel file {1}", customerID, excelFilePath);
MessageBox.Show(message);
}
else
{
String message = String.Format("The Column CustomerID not found in Excel file {0}", excelFilePath);
MessageBox.Show(message);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return null;
}
public class ExcelData
{
public String customerID;
public String customerFirstName;
public String customerLastName;
public String customerAddress;
}
Change your select query to like below -
#"SELECT * FROM [" + excelSheets[0] + "] WHERE CustomerID=<your_value>"
Courtesy msdn web site:
Link: MSDN
DataTable dt;
private void button1_Click(object sender, EventArgs e)
{
try
{
openFileDialog1.ShowDialog();
string connectionString = string.Format("Provider = Microsoft.Jet.OLEDB.4.0;Data Source ={0};Extended Properties = Excel 8.0;", this.openFileDialog1.FileName);
var con = new OleDbConnection(connectionString);
var cmd = new OleDbCommand("select * from [sheet1$] where [MRN#]=#c", con);
cmd.Parameters.Add("#c", "33264");
con.Open();
var dr = cmd.ExecuteReader();
if (dr.HasRows)
{
dt = new DataTable();
dt.Load(dr);
}
dr.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
DataGridView dv = new DataGridView();
this.Controls.Add(dv);
dv.DataSource = dt;
}
}
EDIT:
As per your code you should try the below lines of code:
OleDbCommand _oleCmdSelect = new OleDbCommand(#"SELECT * FROM [" + excelSheets[0] + "]" + " Where [CustomerID#] = #custID" , objConn);
_oleCmdSelect.Parameters.Add("#custID", customerID);
OleDbDataAdapter oleAdapter = new OleDbDataAdapter();
oleAdapter.SelectCommand = _oleCmdSelect;

How to return sql query result messages with c# ASP.net

I tried following code but I couldn't find success messages from it.Here commandText can be insert,update,delete or select query and I need dataset if it is a select query else success messages like in sql result output("12 row(s) inserted successfully").I can't use ExecuteScalar or ExecuteNonQuery methods since I need dataset output when select query executed.
public static DataSet ExecuteDataset(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
using (SqlConnection cn = new SqlConnection(connectionString))
{
cn.InfoMessage += delegate(object sender, SqlInfoMessageEventArgs e)
{
MessageInfo += "\n" + e.Message;
};
cn.FireInfoMessageEventOnUserErrors = true;
cn.Open();
using (SqlCommand command = new SqlCommand(commandText, cn))
{
using (SqlDataAdapter adapter = new SqlDataAdapter(command))
{
DataSet dt = new DataSet();
adapter.Fill(dt); // Do something with DataTable
return dt;
}
}
}
}
I am using System.Data version 4.0.0.0 and the following works for me with UPDATE, INSERT, DELETE and SELECT statements.
using (SqlDataAdapter adapter = new SqlDataAdapter(command))
{
var rowsAffected = -1;
adapter.SelectCommand.StatementCompleted += delegate (object sender, StatementCompletedEventArgs e)
{
rowsAffected = e.RecordCount;
};
DataSet dt = new DataSet();
adapter.Fill(dt); // Do something with DataTable
return dt;
}
I managed to solve it by following way but hope there should be a better way.
string type = Query.Trim().Split(' ')[0].ToLower();
if ( type == "select")
{
DataSet result = SqlHelper.ExecuteDataset(CommandType.Text, Query);
}
else
{
if(type == "insert") type="inserted."; else type=type+"d.";
int a=(int)SqlHelper.ExecuteNonQuery(CommandType.Text, Query);
if (a > 0)
{
lblInfo.Text = "Query executed successfully. " + a.ToString() + " row(s) " + type;
}
}
I found another one.That's better than above one.
query = resultQuery + " SELECT '('+CONVERT(VARCHAR(10),##ROWCOUNT)+' row(s) affected)' AS RESULT";
DataSet result = DataSet result = SqlHelper.ExecuteDataset(CommandType.Text, query);
if (result.DefaultViewManager.DataViewSettingCollectionString.Contains("Table") == true)
{
sqlGrid.Visible = true;
sqlGrid.DataSource = result;
sqlGrid.DataBind();
}
if (sqlGrid.Rows.Count==1 && sqlGrid.Rows[0].Cells.Count==1)
{
string text = (sqlGrid.Rows[0].Cells[0]).Text;
if (text.Contains("row(s) affected"))
{
lblInfo.Text=text;
lblInfo.Visible=true;
sqlGrid.DataSource = null;
sqlGrid.DataBind();
}
}

Categories