Hi i am trying to create a auto fill in my application.
but some how its not filling the array. can someone help me?
i am new to C# so i am sorry for stupid mistakes.
private void autonrTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
try
{
int i = 0;
var check[i];
using (var con2 = new SqlConnection(#"Data Source=DESKTOP-RSEBNR7;Initial Catalog=AudiDealer;Integrated Security=True"))
using (var cmd2 = new SqlCommand("SELECT * FROM auto where autonr = " + autonrTextBox.Text, con2))
{
con2.Open();
check = cmd2.ExecuteScalar();
con2.Close();
autonrTextBox.Text = check[0];
kentekenTextBox.Text = check[1];
merkTextBox.Text = check[2];
modelTextBox.Text = check[3];
kleurTextBox.Text = check[4];
categorieTextBox.Text = check[5];
pkSTextBox.Text = check[6];
apkTextBox.Text = check[7];
kilometerstandTextBox.Text = check[8];
bijtellingTextBox.Text = check[9];
energielabelTextBox.Text = check[10];
}
}
catch
{
MessageBox.Show("Dit Auto nummer komt niet voor in de database. controleer deze en probeer opnieuw","Error");
}
}
You have to use ExecuteReader() even if you want to read a single record (ExecuteScalar returns the single value):
// I've hidden the connection string by ...
using (var con2 = new SqlConnection(#"...")) {
// using will close connection for you, do not call Close() direct
con2.Open();
// Let sql be readable and parametrized
string sql =
#"SELECT *
FROM auto
WHERE autonr = #prm_autonr";
using (var cmd2 = new SqlCommand(sql, con2)) {
cmd2.Parameters.AddWithValue("#prm_autonr", autonrTextBox.Text);
using (var reader = cmd2.ExecureReader()) {
// Do we have any records?
if (reader.Read()) {
// To be on the safe side use Convert.ToString():
// what if the database field is of type Number(8, 5)? NVarChar2(11)?
autonrTextBox.Text = Convert.ToString(reader[0]);
kentekenTextBox.Text = Convert.ToString(reader[1]);
merkTextBox.Text = Convert.ToString(reader[2]);
modelTextBox.Text = Convert.ToString(reader[3]);
kleurTextBox.Text = Convert.ToString(reader[4]);
categorieTextBox.Text = Convert.ToString(reader[5]);
pkSTextBox.Text = Convert.ToString(reader[6]);
apkTextBox.Text = Convert.ToString(reader[7]);
kilometerstandTextBox.Text = Convert.ToString(reader[8]);
bijtellingTextBox.Text = Convert.ToString(reader[9]);
energielabelTextBox.Text = Convert.ToString(reader[10]);
}
}
}
}
You must use ExecuteReader. The ExecuteScalar return only single data. ex: count, sum, min, max. aggregate functions
https://msdn.microsoft.com/en-us/library/9kcbe65k(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar(v=vs.110).aspx
Related
I'm trying to write some code to loop through a data range and add new documents to SAP based on a query input. I need the values to be added to the documents based on the supplier field and when the supplier changes create a new document. Currently I am only able to loop through adding items to the document and rather than moving to the next supplier it just loops the items again. I'm pretty new to C# so looping is pretty new to me but hoping someone can help?
int recordCount = oRecordset.RecordCount;
string Supplier = oRecordset.Fields.Item(1).Value.ToString();
string Item = oRecordset.Fields.Item(0).Value.ToString();
Qty = Convert.ToInt32(oRecordset.Fields.Item(3).Value.ToString());
if(recordCount>0)
application.MessageBox("Adding PQ");
System.Threading.Thread.Sleep(2);
{
for(int i = 0; i < recordCount; i++)
{
OPQT.CardCode = Supplier ;
OPQT.DocDate = DateTime.Now;
OPQT.DocDueDate = DateTime.Now;
OPQT.RequriedDate = DateTime.Now;
OPQT.Lines.ItemCode = Item;
OPQT.Lines.RequiredQuantity = Qty;
OPQT.Lines.Add();
oRecordset.MoveNext();
}
OPQT.Add();
application.MessageBox("PQ Added");
}
You'd be much better of starting to learn with SqlDataReader, IMO.
Adapting to your business case you'd get something like this, this is not working code, I don't have enough info for that. However this should help you progress in the right direction.
using System;
using System.Data;
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString = "Data Source=(local);Initial Catalog=...";
ReadOData( connectionString);
}
private static IEnumerable<OPQT> ReadOrderData(string connectionString)
{
string queryString =
#"
SELECT
T0.[ItemCode],
T0.[CardCode],
'10' [Qty]
FROM
[OSCN] T0
JOIN
[OCRD] T1
ON T0.[CardCode] = T1.[CardCode]
WHERE
T1.[CardType] ='S'";
using (SqlConnection connection =
new SqlConnection(connectionString))
{
SqlCommand command =
new SqlCommand(queryString, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
// Call Read before accessing data.
while (reader.Read())
{
yield return ReadSingleRow((IDataRecord)reader);
}
}
finally
{
// Call Close when done reading.
reader.Close();
}
}
}
private static OPQT ReadSingleRow(IDataRecord dataRecord)
{
return new OPQT
{
Lines.ItemCode = dataRecord[0],
CardCode = dataRecord[1],
Lines.RequiredQuantity = dataRecord[2]
};
}
}
I have a very silly problem. I am doing a select, and I want that when the value comes null, return an empty string. When there is value in sql query, the query occurs all ok, but if there is nothing in the query, I have to give a sqlCommand.CommandTimeout greater than 300, and yet sometimes gives timeout. Have a solution for this?
public string TesteMetodo(string codPess)
{
var vp = new Classe.validaPessoa();
string _connection = vp.conString();
string query = String.Format("SELECT COUNT(*) FROM teste cliente WHERE cod_pess = {0}", codPess);
try
{
using (var conn = new SqlConnection(_connection))
{
conn.Open();
using (var cmd = new SqlCommand(query, conn))
{
SqlDataReader dr = cmd.ExecuteReader();
if(dr.HasRows)
return "";
return codPess;
}
}
}
You should probably validate in the UI and pass an integer.
You can combine the usings to a single block. A bit easier to read with fewer indents.
Always use parameters to make the query easier to write and avoid Sql Injection. I had to guess at the SqlDbType so, check your database for the actual type.
Don't open the connection until directly before the .Execute. Since you are only retrieving a single value you can use .ExecuteScalar. .ExecuteScalar returns an Object so must be converted to int.
public string TesteMetodo(string codPess)
{
int codPessNum = 0;
if (!Int32.TryParse(codPess, out codPessNum))
return "codPess is not a number";
var vp = new Classe.validaPessoa();
try
{
using (var conn = new SqlConnection(vp.conString))
using (var cmd = new SqlCommand("SELECT COUNT(*) FROM teste cliente WHERE cod_pess = #cod_pess", conn))
{
cmd.Parameters.Add("#cod_pess", SqlDbType.Int).Value = codPessNum;
conn.Open();
int count = (int)cmd.ExecuteScalar();
if (count > 0)
return "";
return codPess;
}
}
catch (Exception ex)
{
return ex.Message;
}
}
I am trying to update my database. However when I print object that gets returned by ExecuteNonQuery() it says 0.
Here's my code:
try
{
using(dbConnection = new SqliteConnection(dbConnString))
{
dbConnection.Open();
using(dbCommand = dbConnection.CreateCommand())
{
dbCommand.CommandText = "UPDATE 'GameObject' SET 'LocationX' = #locX, 'LocationY' = #locY, 'LocationZ' = #locZ WHERE 'id' = #id";
dbCommand.Parameters.AddRange(new SqliteParameter[]
{
new SqliteParameter("#locX") { Value = x},
new SqliteParameter("#locY") { Value = y},
new SqliteParameter("#locZ") { Value = z},
new SqliteParameter("#id") {Value = id}
});
int i = dbCommand.ExecuteNonQuery();
Debug.Log(i);
}//end dbcommand
}//end dbconnection
}//end try
catch(Exception e)
{
Debug.Log(e);
}
I think it's because of my where clause, because when I add this clause to a select query, my variables won't get updated. I just can't find what's wrong with it.
select query:
try
{
using(dbConnection = new SqliteConnection(dbConnString))
{
dbConnection.Open();
using(dbCommand = dbConnection.CreateCommand())
{
dbCommand.CommandText = "SELECT * FROM 'GameObject' WHERE 'id' = #id"; //without the where everything works fine
dbCommand.Parameters.Add (new SqliteParameter("#id") { Value = 1});
using(dbReader = dbCommand.ExecuteReader())
{
while(dbReader.Read())
{
id = dbReader.GetInt32(0);
x = dbReader.GetFloat(1);
y = dbReader.GetFloat(2);
z = dbReader.GetFloat(3);
}
}//end dbreader
}//end dbcommand
}//end dbconnection
_object.transform.position = new Vector3(x,y,z);
Debug.Log ("id: " + id + " location: " + _object.transform.position);
}
catch(Exception e)
{
Debug.Log(e);
}
One reason might be from https://www.sqlite.org/lang_keywords.html
For resilience when confronted with historical SQL statements, SQLite
will sometimes bend the quoting rules above:
If a keyword in single quotes (ex: 'key' or 'glob') is used in a
context where an identifier is allowed but where a string literal is
not allowed, then the token is understood to be an identifier instead
of a string literal.
Since none of them is keyword, try to use them without single quotes.
I'm updating some old legacy code and I ran into a problem with the
SqlCommand.ExecuteReader() method. The problem is that it's not returning any
results. However, using SqlDataAdapter.Fill(), I get results back from the
database. What am I doing wrong? How can I get results back using the data
reader?
var connectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ToString();
using (var sqlConnection = new SqlConnection(connectionString))
{
using (var sqlCommand = new SqlCommand())
{
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandType = CommandType.Text;
sqlCommand.CommandText = "SELECT * FROM MyTable WHERE ID = 1";
sqlConnection.Open();
// This code works.
//var dataTable = new DataTable();
//using (var sqlDataAdapter = new SqlDataAdapter(sqlCommand))
//{
// sqlDataAdapter.Fill(dataTable);
//}
// This code is not working.
using (var sqlDataReader = sqlCommand.ExecuteReader())
{
while (sqlDataReader.Read())
{
// This fails because the data reader has no results.
var id = sqlDataReader.GetInt32(0);
}
}
}
}
Could it be that there is no Int32 in your results ?
var id = sqlDataReader.GetInt32(0); // <-- this might not be an Int32
Either try:
var id = sqlDataReader.GetValue(0);
Or cast to the correct type (BIGINT for example is Int64), not sure without seeing your data.
Try this..
var id = 0;
using (var sqlDataReader = sqlCommand.ExecuteReader())
{
while (sqlDataReader.Read())
{
id = sqlDataReader.GetInt32(sqlDataReader.GetOrdinal("ColName"));
}
}
I have moved the variable outside of the reader code or the variable will only be accessible inside that scope. I would avoid specifying the ordinal in the code, in case someone altered the columns in the DB.
Also, specify the columns in the SQL statement... SELECT ColName FROM ... and use params in the query
If you got to that line then it has results
Does not mean the value is not null
And you should not use a SELECT *
If may have a problem with an implicit cast
Try Int32
try
{
if(sqlDataReader.IsDBNull(0))
{
// deal with null
}
else
{
Int32 id = sqlDataReader.GetInt32(0);
}
}
catch (SQLexception Ex)
{
Debug.WriteLine(Ex.message);
}
var connectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ToString();
using (var sqlConnection = new SqlConnection(connectionString))
{
sqlConnection.Open();
string sql = "SELECT * FROM MyTable WHERE ID = 1";
using (var sqlCommand = new SqlCommand(sql, sqlConnection))
{
using (var sqlDataReader = sqlCommand.ExecuteReader())
{
while (sqlDataReader.Read())
{
// This fails because the data reader has no results.
var id = sqlDataReader.GetInt32(0);
}
}
}
}
I have tried several ways to do this but some reason I am not able to correctly implement the If statement.
I am trying to acquire the SelectedItem.Text from Drop Down List and then search in the database for that row and store it in DataSet and then display it on a GridView. However, the database has 19 fixed columns with words, so if the user selects one drop down listing in the if statement the DataSet should get displayed on a GridView but if the data is not found in the database Else an error message should pop up saying "Data Not Found"
I have tried physically inputting the 19 fixed columns in an Array and using the following:
protected void SearchProductButton_Click1(object sender, EventArgs e)
{
string Producttext = SearchProductDropDownList.SelectedItem.Text;
string[] Producttext2 =
{
"Chem",
"Drill",
"Elect",
"Products",
"Environmental",
"Instrument",
"Lab",
"Lift",
"Tools",
"Repair",
"Pipes",
"Portable",
"Power",
"Steel",
"Testing",
"Tooling",
"Tubes",
"Valves",
"Systems",
"Consumables",
};
using (var con = new SqlConnection("Data Source=localhost;Initial Catalog=ROG;Integrated Security=True"))
using (var daProduct = new SqlDataAdapter("SELECT [Serial_No], [Material_No], [Product_Line], [Product_Description], [Size], [UOM], [Supplier_Price], [Price_Date], [Selling_Price] FROM [ProductDB] WHERE [Product_Line] = #Product_Line", con))
{
foreach (string x in Producttext2)
{
if (x.Contains(Producttext))
{
daProduct.SelectCommand.Parameters.Add("#Product_Line", SqlDbType.VarChar, 50).Value = Producttext;
DataSet dsProduct = new DataSet();
daProduct.Fill(dsProduct, "Product_Line");
SearchProductGridView.DataSource = dsProduct;
SearchProductGridView.DataBind();
}
else
{
MessageBox.Show("Data Not Found");
}
}
}
}
In the SQL data I only have information filled for Chem & Elect so all the other ones should show an error but due to the Foreach the xvalue` is not clearing and stays at the first run value so it ends up skipping until it goes through the whole list.
I have modified the code after reading about the string to string array and then checking the index if it is greater then -1 continue or else show the error.
Here's the code:
protected void SearchProductButton_Click1(object sender, EventArgs e)
{
string Producttext = SearchProductDropDownList.SelectedItem.Text;
string[] Productarray = new string[20];
Productarray[0] = "Chem";
Productarray[1] = "Drill";
Productarray[2] = "Elect";
Productarray[3] = "Products";
Productarray[4] = "Environmental";
Productarray[5] = "Instrument";
Productarray[6] = "Lab";
Productarray[7] = "Lift";
Productarray[8] = "Tools";
Productarray[9] = "Repair";
Productarray[10] = "Pipes";
Productarray[11] = "Portable";
Productarray[12] = "Power";
Productarray[13] = "Steel";
Productarray[14] = "Testing";
Productarray[15] = "Tooling";
Productarray[16] = "Tubes";
Productarray[17] = "Valves";
Productarray[18] = "Systems";
Productarray[19] = "Consumables";
using (var con = new SqlConnection("Data Source=localhost;Initial Catalog=ROG;Integrated Security=True"))
using (var daProduct = new SqlDataAdapter("SELECT [Serial_No], [Material_No], [Product_Line], [Product_Description], [Size], [UOM], [Supplier_Price], [Price_Date], [Selling_Price] FROM [ProductDB] WHERE [Product_Line] = #Product_Line", con))
{
//foreach (string x in Producttext2)
//{
int index1 = Array.IndexOf(Productarray, Producttext);
if (index1 !=-1)
{
daProduct.SelectCommand.Parameters.Add("#Product_Line", SqlDbType.VarChar, 50).Value = Producttext;
DataSet dsProduct = new DataSet();
daProduct.Fill(dsProduct, "Product_Line");
SearchProductGridView.DataSource = dsProduct;
SearchProductGridView.DataBind();
}
else
{
MessageBox.Show("Data Not Found");
}
//}
}
}
The problem with the second approach is that it never goes to the else statement no matter what I try.
Edit:
I have decided to approach my requirement in a different way, instead of using Textbox I have sorted to using ComboBox from AJAX ToolKit.
Here's the HTML:
<ajaxToolkit:ComboBox ID="SearchMaterialComboBox" runat="server"
AutoCompleteMode="Append" AutoPostBack="false" CaseSensitive="false"
DataSourceID="ProductDBMaterialSqlDataSource" DataTextField="Material_No"
DataValueField="Material_No" DropDownStyle="DropDownList" Height="20px"
MaxLength="10" RenderMode="Block" style="display: inline-block;" Width="285px">
</ajaxToolkit:ComboBox>**strong text**
Code:
protected void SearchMaterialButton_Click(object sender, EventArgs e)
{
//long Materialtextbox = Convert.ToInt64(SearchMaterialComboBox.Text);
string Materialstr = SearchMaterialComboBox.Text;
using (var con = new SqlConnection("Data Source=localhost;Initial Catalog=ROG;Integrated Security=True"))
using (var daMaterial = new SqlDataAdapter("SELECT [Serial_No], [Material_No], [Product_Line], [Product_Description], [Size], [UOM], [Supplier_Price], [Price_Date], [Selling_Price] FROM [ProductDB] WHERE [Material_No] = #Material_No", con))
{
if (Materialstr != "")
{
daMaterial.SelectCommand.Parameters.Add("#Material_No", SqlDbType.BigInt).Value = Materialstr;
DataSet dsMaterial = new DataSet();
daMaterial.Fill(dsMaterial, "Material_No");
SearchProductGridView.DataSource = dsMaterial;
SearchProductGridView.DataBind();
}
else
{
}
}
}
I believe the last post mentioned by #Patashu had a valid point by inserting in the HasRows a value of 0, if it is not 0 then continue else show an error message. However, the current approach has the AutoComplete option which is neat comparing to the conventional TextBox approach.
using System.Linq;
string match = Producttext2.FirstOrDefault((x) => x.Contains(Producttext));
if (match != null)
{
// do stuff
}
else
{
// error message
}
Method from http://msdn.microsoft.com/en-us/library/bb549039.aspx