Loop on field change C# - c#

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]
};
}
}

Related

how to add values from database to a list in unity

i have a data base in which i created a table
"CampWheelDenominationno", i have a specific row "quota"
i need to take the "slno" of corresponding "quota" when ever "quota"
becomes zero.
my sql code to do that is
"select slno from CampWheelDenomination where quota_allowded = 0"
now i need to add these "slno" to a list..i have done a method my own but t doesn't works
public int checkCodeinDb()
{
using (IDbConnection dbConnection = new SqliteConnection (connectionString))
{
dbConnection.Open ();
using (IDbCommand dbCmd = dbConnection.CreateCommand ())
{
string sqlQuery = "select slno from CampWheelDenomination where quota_allowded = 0";
dbCmd.CommandText = sqlQuery;
using (IDataReader reader = dbCmd.ExecuteReader ())
{
while (reader.Read ())
{
//slnolist is a list i have created at begining
SlNoList.Add (reader.GetString (0));
}
return slnolist ; //error at here
foreach (string st in SlNoList)// i have done this to check whether the slno is added to the list.
{
print (st);
}
dbConnection.Close ();
reader.Close ();
}
}
}
}
how to add these slno from the databse to the SlNOList
error is Cannot implicitly convert type System.Collections.Generic.List<string>' toint' occuring at line return SlNoList
Your are trying to trying to return List but you function return type is int. Change you function definition as follows:
public List<string> checkCodeinDb()
{
///your usual code here
Also looking at your code you probably should have a List inside your function and return it.
Example:
List<string> slnolist = checkCodeinDb();
public List<string> checkCodeinDb()
{
List<string> data;
///your usual code here and add your database returned value to data variable and finally return it
return data;
}
and also to add the values from database to list we can use this code
public void checkCodeinDb()
{
using (IDbConnection dbConnection = new SqliteConnection (connectionString))
{
dbConnection.Open ();
using (IDbCommand dbCmd = dbConnection.CreateCommand ())
{
string sqlQuery = "select slno from CampWheelDenomination where quota_allowded = 0";
dbCmd.CommandText = sqlQuery;
using (IDataReader reader = dbCmd.ExecuteReader ())
{
while (reader.Read ())
{
string ad = reader ["slno"].ToString();
SlNoList.Add (ad);
}
foreach (string st in SlNoList)
{
print (st);
}
dbConnection.Close ();
reader.Close ();
}
}
}
}

SQL Sever read data to array in C#

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

WebMethod failure

I have the following webmethod on a asmx page that will not connect to my database. Can anyone shed any light on where I have gone wrong.
[WebMethod]
public int[] getEmployeeIDs()
{
Connection conn = new Connection();
Recordset rs = new Recordset();
conn.ConnectionString = "Data Source=MyWebBasedServer;Initial Catalog=MyDatabase;Persist Security Info=False;User ID=MyLogin;Password=MyPassword";
rs.Open("SELECT ID from MyTable", conn, CursorTypeEnum.adOpenStatic);
int[] ID = new int[rs.RecordCount];
int i = 0;
while (!rs.EOF)
{
ID[i++] = rs.Fields["ID"].Value;
rs.MoveNext();
}
rs.Close();
conn.Close();
return ID;
}
Error message I get is
The connection cannot be used to perform this operation. It is either
closed or invalid in this context. (Pointing to "int[] ID = new
int[rs.RecordCount];")
Thanks.
The code below shows two common ways to retrieve a result set from a SELECT statement in ADO.Net.
There's a website called ConnectionStrings.com that shows all the various ways to connect to SQL Server, along with many other kinds of databases.
If you're new to C# programming, the using statement is a great way to avoid resource leaks when handling objects that implement IDisposable.
Returning complex types from a WebMethod might result in an error. The method's underlying XML serializer might not know how to handle certain types. In that case, XmlIncludeAttribute can be used to provide explicit type information. Here's an MSDN thread discussing how to go about that.
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web.Services;
namespace ConsoleApplication19
{
public class Program
{
public static void Main(String[] args)
{
var connectionString = "Data Source=MyWebBasedServer;Initial Catalog=MyDatabase;Persist Security Info=False;User ID=MyLogin;Password=MyPassword;";
var a = GetEmployeeIDs_Version1(connectionString);
var b = GetEmployeeIDs_Version2(connectionString);
}
/* Version 1
Use a "while" loop to fill a WebData list and return it as an array. */
[WebMethod]
private static WebData[] GetEmployeeIDs_Version1(String connectionString)
{
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
var commandText = "SELECT ID, SurName from MyTable";
using (var command = new SqlCommand() { Connection = connection, CommandType = CommandType.Text, CommandText = commandText })
{
using (var reader = command.ExecuteReader(CommandBehavior.CloseConnection))
{
var result = new List<WebData>();
while (reader.Read())
result.Add(new WebData() { ID = Convert.ToInt32(reader["ID"]), Surname = reader["Surname"].ToString() });
return result.ToArray();
}
}
}
}
/* Version 2
Fill a DataSet with the result set.
Because there's only one SELECT statement, ADO.Net will
populate a DataTable with that result set and put the
DataTable in the dataset's Tables collection.
Use LINQ to convert that table into a WebData array. */
[WebMethod]
private static WebData[] GetEmployeeIDs_Version2(String connectionString)
{
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
var commandText = "SELECT ID, SurName from MyTable";
using (var command = new SqlCommand() { Connection = connection, CommandType = CommandType.Text, CommandText = commandText })
{
using (var adapter = new SqlDataAdapter())
{
var dataSet = new DataSet();
adapter.SelectCommand = command;
adapter.Fill(dataSet);
return
dataSet
// There should only be one table in the dataSet's Table's collection.
.Tables[0]
.Rows
// DataTable isn't LINQ-aware. An explicit cast is needed
// to allow the use of LINQ methods on the DataTable.Rows collection.
.Cast<DataRow>()
// The rows in a DataTable filled by an SqlDataAdapter
// aren't strongly typed. All of a row's columns are
// just plain old System.Object. Explicit casts are necessary.
.Select(row => new WebData() { ID = Convert.ToInt32(row["ID"]), Surname = row["Surname"].ToString() })
// Use LINQ to convert the IEnumerable<WebData> returned by
// the .Select() method to an WebData[].
.ToArray();
}
}
}
}
}
public class WebData
{
public Int32 ID { get; set; }
public String Surname { get; set; }
}
}

Two queries to two lists?

At the moment, I have this which works fine:
using (connection = new SqlConnection("connection string here"))
{
using (command = new SqlCommand(#"select * from tbl1", connection))
{
connection.Open();
using (reader = command.ExecuteReader())
{
while (reader.Read())
{
int ColIndex1 = reader.GetOrdinal("col_1");
int ColIndex2 = reader.GetOrdinal("col_2");
Console.Write(reader.GetString(ColIndex1);
Console.Write(" - ");
Console.Write(reader.GetString(ColIndex2);
Console.Write(Environment.NewLine);
}
}
}
}
I have another query which I run separately, but that second query needs the first query, which means I end up running the first query twice. To avoid that, if I changed the command line to:
using (command = new SqlCommand(#"select * from tbl1; select * from tbl2", connection))
How do I get each query into a separate list? I understand how to get a single query into a list, i.e:
public class Data
{
public int ColumnIndex1 { get; set; }
public int ColumnIndex2 { get; set; }
}
List<Data> list = new List<Data>();
list.Add(new Data(ColIndex1, ColIndex2));
The first query is used to create directories on the hard drive. The second query then uses the first query and then adds files to the created directories.
using (connection = new SqlConnection("connection string here"))
{
using (command = new SqlCommand(#"select * from tbl1", connection))
{
connection.Open();
using (reader = command.ExecuteReader())
{
while (reader.Read())
{
// read first grid
}
if(reader.NextResult())
{
while (reader.Read())
{
// read second grid
}
}
}
}
}
However, I strongly suggest using helper tools, for example, via "dapper":
List<FirstType> first;
List<FirstType> second;
using(var multi = connection.QueryMultiple(sql, args))
{
first = multi.Read<FirstType>().ToList();
second = multi.Read<SecondType>().ToList();
}
I think you need to investigate the NextResult method on the IDataReader interface. This allows you to move through multiple result sets.
http://msdn.microsoft.com/en-us/library/system.data.idatareader.nextresult(v=vs.110).aspx

Value is zero after filter SQL in C#

I`m new in C#..
I have write function to filter department. And this function will return idDepartment.
New problem is, department keep value "System.Windows.Forms.Label, Text : ADMIN ", that`s why i got zero. So how can i take "ADMIN" only and keep to department?
Update :
public partial class frmEditStaff : Form
{
private string connString;
private string userId, department; //Department parameter coming from here
private string conString = "Datasource";
public frmEditStaff(string strUserID, string strPosition)
{
InitializeComponent();
//Pass value from frmListStaff to userID text box
tbStaffId.Text = strUserID.ToString();
userId = strUserID.ToString();
department = strPosition.ToString();
}
This code below is working, don`t have any problem.
public int lookUpDepart()
{
int idDepart=0;
using (SqlConnection openCon = new SqlConnection(conString))
{
string lookUpDepartmenId = "SELECT idDepartment FROM tbl_department WHERE department = '" + department + "';";
openCon.Open();
using (SqlCommand querylookUpDepartmenId = new SqlCommand(lookUpDepartmenId, openCon))
{
SqlDataReader read = querylookUpDepartmenId.ExecuteReader();
while (read.Read())
{
idDepart = int.Parse(read[0].ToString());
break;
}
}
openCon.Close();
return idDepart;
}
}
Thanks for help. Happy nice day!
Concerning your problem : department keep value "System.Windows.Forms.Label, Text : ADMIN "
You have problem right in this call frmEditStaff(strUserID,yourLabel.ToString());
Although you have not shared your call for this function/Constructor, yet it seems your second parameter is going wrong in this call. Do not use ToString() here. Rather you have to use .Text as
frmEditStaff(strUserID,yourLabel.Text);
That will solve your problem. I knew it because usually programmers have experience of making this mistake :)
When selecting a single value from a single row, you can use the ExecuteScalar method, that does all that for you, like this:
using (SqlCommand querylookUpDepartmenId = new SqlCommand(lookUpDepartmenId, openCon))
{
idDepart = int.Parse(querylookUpDepartmenId.ExecuteScalar());
}
And again, using string concatenation in SQL queries is just plain wrong
And for your updated question: Try using the Text property of the label, insead of the .ToString() method.
I would recommend getting a good tutorial book about C# / .net, and following the examples there.
public int lookUpDepart()
{
int idDepart = 0;
using (SqlConnection con = new SqlConnection(conString))
{
string lookUpDepartmenId = "SELECT idDepartment FROM tbl_department WHERE department = " + department;
con.Open();
using (SqlCommand querylookUpDepartmenId = new SqlCommand(lookUpDepartmenId, openCon))
{
SqlDataReader read = querylookUpDepartmenId.ExecuteReader();
while (read.Read())
{
idDepart = Convert.ToInt32((read[0]).ToString());
break;
}
}
con.Close();
return idDepart;
}
}
Try the above code, I reworked it. It is working for me...

Categories