DataTable returns "0" as value - c#

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.

Related

output deleted variable from sql query does not work in c#

I have this query in my c# asp.net server. When I run it on the server it output the inserted status and not the deleted one as expected. when I run the same query on the Microsoft management SQL studio it works just fine.
Any suggestions for what could be wrong?
public override BaseMessageStatus SetHubMessageStatus(Participant toParticipant, Transaction transaction, Ticket ticket, BaseMessageStatus nextStatus)
{
BaseMessageStatus originalStatus = BaseMessageStatus.Undefined;
SqlConnection sqlConnecntion = SQL_CONNECTION;
string stquery = #"update [webMessages] set [status]=#status OUTPUT Deleted.status
where [sessionId]=#sessionId and [transactionId]=#transactionId and [toPartID]=#toParticipantID";
//new DataTable
DataTable dt = new DataTable();
using (sqlConnecntion)
{
using (SqlCommand cmd = new SqlCommand(stquery))
{
cmd.Connection = sqlConnecntion;
cmd.Parameters.AddWithValue("#sessionId", ticket.id);
cmd.Parameters.AddWithValue("#transactionId", transaction.id);
cmd.Parameters.AddWithValue("#toParticipantID", toParticipant.id);
cmd.Parameters.AddWithValue("#status", (int)nextStatus);
try
{
sqlConnecntion.Open();
cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(dt);
if (dt != null && dt.Rows.Count > 0)
{
if (dt.Rows[0]["status"] != null && dt.Rows[0]["status"] != DBNull.Value)
{
Enum.TryParse<BaseMessageStatus>(dt.Rows[0]["status"].ToString(), out originalStatus);
}
}
sqlConnecntion.Close();
}
catch (Exception ex)
{
Logger.Error(ex);
}
}
}
return originalStatus;
}

How do you programmatically check if a spreadsheet has headers in C#

I am creating a winform application where every day, a user will select a xlsx file with the day's shipping information to be merged with our invoicing data.
The challenge I am having is when the user does not download the xlsx file with the specification that the winform data requires. (I wish I could eliminate this step with an API connection but sadly I cannot)
My first step is checking to see if the xlsx file has headers to that my file path is valid
Example
string connString = "provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + *path* + "';Extended Properties='Excel 12.0;HDR=YES;';";
Where path is returned from an OpenFileDialog box
If the file was chosen wasn't downloaded with headers the statement above throws an exception.
If change HDR=YES; to HDR=NO; then I have trouble identifying the columns I need and if the User bothered to include the correct ones.
My code then tries to load the data into a DataTable
private void loadRows()
{
for (int i = 0; i < deliveryTable.Rows.Count; i++)
{
DataRow dr = deliveryTable.Rows[i];
int deliveryId = 0;
bool result = int.TryParse(dr[0].ToString(), out deliveryId);
if (deliveryId > 1 && !Deliveries.ContainsKey(deliveryId))
{
var delivery = new Delivery(deliveryId)
{
SalesOrg = Convert.ToInt32(dr[8]),
SoldTo = Convert.ToInt32(dr[9]),
SoldName = dr[10].ToString(),
ShipTo = Convert.ToInt32(dr[11]),
ShipName = dr[12].ToString(),
};
Which all works only if the columns are in the right place.
If they are not in the right place my thought is to display a message to the user to get the right information
Does anyone have any suggestions?
(Sorry, first time posting a question and still learning to think through it)
I guess you're loading the spreadsheet into a Datatable? Hard to tell with one line of code. I would use the columns collection in the datatable and check to see if all the columns you want are there. Sample code to enumerate the columns below.
private void PrintValues(DataTable table)
{
foreach(DataRow row in table.Rows)
{
foreach(DataColumn column in table.Columns)
{
Console.WriteLine(row[column]);
}
}
}
private void GetExcelSheetForUpload(string PathName, string UploadExcelName)
{
string excelFile = "DateExcel/" + PathName;
OleDbConnection objConn = null;
System.Data.DataTable dt = null;
try
{
DataSet dss = new DataSet();
String connString = "Provider=Microsoft.ACE.OLEDB.12.0;Persist Security Info=True;Extended Properties=Excel 12.0 Xml;Data Source=" + PathName;
objConn = new OleDbConnection(connString);
objConn.Open();
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return;
}
String[] excelSheets = new String[dt.Rows.Count];
int i = 0;
foreach (DataRow row in dt.Rows)
{
if (i == 0)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + excelSheets[i] + "]", objConn);
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmd;
oleda.Fill(dss, "TABLE");
}
i++;
}
grdExcel.DataSource = dss.Tables[0].DefaultView;
grdExcel.DataBind();
lblTotalRec.InnerText = Convert.ToString(grdExcel.Rows.Count);
}
catch (Exception ex)
{
ViewState["Fuletypeidlist"] = "0";
grdExcel.DataSource = null;
grdExcel.DataBind();
}
finally
{
if (objConn != null)
{
objConn.Close();
objConn.Dispose();
}
if (dt != null)
{
dt.Dispose();
}
}
}
if (grdExcel.HeaderRow.Cells[0].Text.ToString() == "CODE")
{
GetExcelSheetForEmpl(PathName);
}
else
{
divStatusMsg.Style.Add("display", "");
divStatusMsg.Attributes.Add("class", "alert alert-danger alert-dismissable");
divStatusMsg.InnerText = "ERROR !!... Upload Excel Sheet in header Defined Format ";
}

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