Get Names ForEach Checked item in Checkedlistbox - c#

I want to get the names associated with the states i select in my program. Below is the code that i currently have. My database has multiple locations within a state that have different contacts. I just want to select a state and acquire everyone under that state. Thanks for the help!
con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\\Database\\LocNo.accdb");
con.Open();
foreach (Object c in checkedListBox2.CheckedItems)
{
if (checkedListBox2.GetItemCheckState(checkedListBox2.Items.IndexOf(c)) == CheckState.Checked)
{
str1 += c.ToString() + ",";
flag = 1;
}
}
i = 0;
allSelectedtypestring = "";
allSelected = str1.Split(',');
while (allSelected.Length - 1 > i)
{
str = "select c1 from table where state ='" + allSelected[i++] + "'";
cmd = new OleDbCommand(str, con);
dr = cmd.ExecuteReader();
dr.Read();
allSelectedtypestring += dr.GetString(11);
}
label30.Text = Convert.ToString(allSelectedtypestring);
con.Close();

You can use the following code to retrieve the contacts:
var states = new List<string>();
foreach (Object c in checkedListBox2.CheckedItems)
{
states.Add(c.ToString());
flag = 1; // Can also be substituted by states.Count > 0
}
using(var con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\\Database\\LocNo.accdb"))
{
con.Open();
using(var cmd = con.CreateCommand())
{
var paramIndex = 0;
var paramClause = new System.Text.StringBuilder(100);
foreach(var state in states)
{
if (paramClause.Length > 0)
paramClause.Append(", ");
paramClause.Append("?");
var paramName = "State" + (paramIndex++).ToString();
cmd.Parameters.AddWithValue(paramName, state);
}
var paramsClause = string.Join(", ", cmd.Parameters.
cmd.CommandText = "select distinct c1 from table where state IN (" + paramsClause.ToString() + ")";
using(var rdr = cmd.ExecuteReader())
{
var contacts = new List<string>();
while(rdr.Read())
{
contacts.Add(rdr.GetString(0);
}
label30.Text = string.Join(", ", contacts);
}
}
}
Please note that I've made the following changes:
Added using statements to reliably dispose the connection, command and reader.
Used a List<string> as a more convenient way to collect the selected states.
Added DISTINCT to the SELECT in order to filter duplicate entries.
Used a parameter in the command text in order to avoid SQL injection attacks. Though this way to use a parameter with an IN clause works for SQL Server, I haven't checked whether it also works for an Access database. Let me know in the comments if it doesn't work.

Related

How do I pull data from mysql and assign it to corresponding values

Good Day.
I have a stock list in mysql database
I then have a windows form where i can allocate stock to a certain job, i do this by pulling all from my parts list in mysql and checking if the item selected by the user is in stock, i then add that item to a list using listbox.Items.Add(myitem). In also ass the quantity the user wants to a different list.
When I allocate the stock to a job i create one string separated by ',' and store that to mysql and the same with my quantites resulting is a parts string that looks like: 'PART001,PART002,PART003' and my quantities like: '2,1,3'.
I then add that to a request list which the admin needs to approve.
My problem comes in where the request form is loaded, I pull these parts and quantity lists from mySql and split them wit myString.Split(',');
And I then just add them to another listbox, HOWEVER when i get the quantities that my stock table has available, I loop over the part numbers and pull the quantities but if I for example have my first part as item 3 in my stock table and my second item as my 1st item in my stock list, it will assign item 1's quantity to my item 3. So basically my loop does not assign the right values.
Here is my code for checking the values
ListBox lb = PartsListBox;
ListBox lbq = PartsQuanListBox;
String query = "SELECT * FROM parts WHERE partnum = '"+PartsSelectCb.Text.Trim()+"'";
String partnum = "N/A";
int quan = 0;
MySqlConnection con = new MySqlConnection(conString);
con.Open();
MySqlCommand cmd = new MySqlCommand(query, con);
MySqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
partnum = (String)dr["partnum"];
}
con.Close();
if(PartsSelectCb.Text == partnum)
{
quan = int.Parse(textBox1.Text);
if (quan > 0)
{
if (!lb.Items.Contains(PartsSelectCb.Text.Trim()))
{
lb.Items.Add(PartsSelectCb.Text.Trim());
lbq.Items.Add(textBox1.Text.Trim());
}
}
}
And here is my code for inserting those values into my request table
private void SendRequest()
{
String dte = DateTime.Now.ToShortDateString();
String g = "";
String h = "";
String a = "";
String b = "";
if (PartsListBox.Items.Count > 0)
{
foreach (var item in PartsListBox.Items)
{
g += item.ToString() + ",";
}
h = g.Substring(0, g.Length - 1);
}
if (PartsQuanListBox.Items.Count > 0)
{
foreach (var itemt in PartsQuanListBox.Items)
{
a += itemt.ToString() + ",";
}
b = a.Substring(0, a.Length - 1);
}
String query = "INSERT INTO partsbook VALUES (NULL,'" + h + "','" + b + "','"
+ ReqTxt.Text.Trim() + "','" + userN + "','" + dte + "','" +""+"','"+ "REQUEST" + "')";
MySqlConnection dataCon = new MySqlConnection(conString);
dataCon.Open();
MySqlCommand cmd = new MySqlCommand(query, dataCon);
try
{
cmd.ExecuteNonQuery();
pmf.CheckRequests();
this.Close();
}
catch (Exception r)
{
MessageBox.Show("ERROR :" + r.Message.ToString());
}
dataCon.Close();
MessageBox.Show("REQUEST SENT");
this.Close();
}
Then on the request side
private void GetStock()
{
String query = "SELECT * FROM parts";
String qtys = "";
MySqlConnection con = new MySqlConnection(conString);
con.Open();
MySqlCommand cmd = new MySqlCommand(query, con);
MySqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
String nme = (String)dr["partnum"];
foreach(var item in UPartsListBox.Items)
{
if(item.ToString() == nme)
{
int q = (int)dr["qty"];
qtys += q.ToString() + ",";
}
}
}
con.Close();
string[] words = qtys.Split(',');
foreach(var word in words)
{
if(word != "")
{
SPartsQuanListBox.Items.Add(word);
}
}
}
User Request:
Admin View:
Stock Table:

OleDbCommand with 'where in' and dbParameter

I try to delete some rows from a table in an access database file via C#.
This attempt fails with no error which leads me to the conclusion that I have a valid query with incorrect data.
I tried to see if I can query the data with a select statement from my code and I can narrow the problem down to the parameters.
The statement should look as follows
SELECT * FROM tbIndex where pguid in ('4a651816-e15b-4c6a-85c4-74033ca6c423', '0add7bff-a22f-4238-9c7f-e1ff4ed3c7e2', '742fae8b-2692-4a6f-802c-848fad570696', '5e6b65de-2403-4800-a47d-e57c7bd8e0a6')
I tried two different ways*(dbCmd2 and dbCmd3)* from which the first*(dbCmd2)* works but is, due to injection problems, not my prefered solution.
using (OleDbCommand dbCmd2 = new OleDbCommand { Connection = m_Connection })
{
dbCmd2.CommandText = "SELECT * FROM tbIndex where pguid in ("+pguid+")";
using (DbDataReader reader = dbCmd2.ExecuteReader())
{
List<object[]> readValuesFromIndex = new List<object[]>();
while (reader.Read())
{
//Point reached
object[] arr = new object[reader.VisibleFieldCount];
reader.GetValues(arr);
//...
}
reader.Close();
}
using (OleDbCommand dbCmd3 = new OleDbCommand { Connection = m_Connection })
{
dbCmd3.CommandText = "SELECT * FROM tbIndex where pguid in (#pguid)";
dbCmd3.Parameters.Add("#pguid", OleDbType.VarChar).Value = pguid;
using (DbDataReader reader = dbCmd3.ExecuteReader())
{
List<object[]> readValuesFromIndex = new List<object[]>();
while (reader.Read())
{
//Point not reached
object[] arr = new object[reader.VisibleFieldCount];
reader.GetValues(arr);
//...
}
reader.Close();
}
}
Note that pguid is set to "'4a651816-e15b-4c6a-85c4-74033ca6c423', '0add7bff-a22f-4238-9c7f-e1ff4ed3c7e2', '742fae8b-2692-4a6f-802c-848fad570696', '5e6b65de-2403-4800-a47d-e57c7bd8e0a6'".
I always thought that the second option would simply replace the parameter in a safe manner but this is obviously not the case.
My question is:
Why doesn't the second option return any values?
A parameter always is a single value.
An in clause requires multiple values, separated by comma's.
You can do something like the following to pass them like separate parameters:
string[] guids = pguid.Split(',');
string sqlin = "";
int paramno = -1;
foreach (var guid in guids)
{
parametercount ++;
sqlin = sqlin + "#Param" + (string)parametercount; + ","
}
dbCmd3.CommandText = "SELECT * FROM tbIndex where pguid in (" + sqlin.Substring(0, sqlin.Length-1) + ")";
for(int i = 0; i <= parametercount; i++){
dbCmd3.Parameters.Add("#Param" + (string)i, OleDbType.VarChar).Value = guids[i].Replace("'", "");
}

how to create an id to be shown in the text box based on selected dropdownlist

i would like to create an id generator based on their department selected from the dropdownlist. lets say my ddl has 3 departments (A,B,C) and when generating an id it will be A20181001 and then A20181002 upon submission but when i pick B from the ddl after sending A20181001 to the database, it will be B20181001.
so far i have created the code for the increment for the id without the departments. here is the code i did so far. (I used the date for today so the 20181001 is just an example):
void getMRF_No()
{
string year = DateTime.Now.Date.ToString("yyyyMMdd");
int mrf = 0;
int i;
string a;
//string x = Request.QueryString["BUnit"];
string mrfNo = "";
database db = new database();
string conn = dbe.BU();
SqlConnection connUser = new SqlConnection(conn);
SqlCommand cmd = connUser.CreateCommand();
SqlDataReader sdr = null;
string query = "SELECT TOP 1 MRF_NO FROM incMRF ORDER BY MRF_NO DESC";
connUser.Open();
cmd.CommandText = query;
sdr = cmd.ExecuteReader();
while (sdr.Read())
{
mrfNo = sdr.GetInt32(0).ToString();
}
if (mrfNo == "")
{
mrfNo = Convert.ToString(year) + "" + 00;
}
mrf += 0;
i = Convert.ToInt32(mrfNo) + 1;
a = i.ToString();
txtMRFNo.Text = a;
connUser.Close();
}
any help to improve this code will be helpful. thank you :)
EDIT:
here is the dropdown list code:
void SelectBU()
{
string database = dbe.BU ();
using (SqlConnection con = new SqlConnection(database))
{
con.Open();
string query = "select BUnit from BusinessUnit";
using (SqlDataAdapter sda = new SqlDataAdapter(query, con))
{
DataSet ds = new DataSet();
sda.Fill(ds, "BUnit");
ddlBu.DataSource = ds;
ddlBu.DataTextField = "BUnit";
ddlBu.DataValueField = "BUnit";
ddlBu.DataBind();
selectOption(ddlBu, "Select Dept");
}
con.Close();
}
}
EDIT2: I will state what im searching for here incase some doesnt know or understand. What i want is upon selecting a department from a dropdownlist, for example i picked A. the textbox show show A2018102201. if i select B it should show B2018102201 and if its C then c2018102201. and it will change its number once i submit it to a database and a new form loads. So if A2018102201 is already in the database, then the text shown in the text box will be A2018102202. BUT if i select B then the textbox will show B2018102201 since it does not exist in the database yet.
First you should get max ID, then increase the numeric part of your Id, and If this is a multi-user application, you have to lock your table, because it might create many ID duplication, Therefore I'm not recommend to create ID like this on c#, it is better to create a Sequence on SQL server. but I wrote this sample for you, just call it with proper value.
static string getMRF_No(string prefixCharFromDropDownList)
{
string year = DateTime.Now.Date.ToString("yyyyMMdd");
string mrfNo = "";
SqlConnection connUser = new SqlConnection("Server=130.185.76.162;Database=StackOverflow;UID=sa;PWD=$1#mssqlICW;connect timeout=10000");
SqlCommand cmd = new SqlCommand(
$"SELECT MAX(MRF_NO) as MaxID FROM incMRF where MRF_NO like '{prefixCharFromDropDownList}%'"
,connUser
);
connUser.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
mrfNo = sdr["MaxID"].ToString();
}
if (mrfNo == "")
{
mrfNo = prefixCharFromDropDownList + year + "000";
}
else
{
mrfNo = prefixCharFromDropDownList + (long.Parse(mrfNo.Substring(1)) + 1).ToString().PadLeft(2);
}
sdr.Close();
cmd = new SqlCommand($"INSERT INTO incMRF (MRF_NO) values ('{mrfNo}')",connUser);
cmd.ExecuteNonQuery();
connUser.Close();
//txtMRFNo.Text = prefixCharFromDropDownList + i.ToString();
return mrfNo;
}
I call this method on a console application as test.
static void Main(string[] args)
{
// send dropdown (selected char) as prefix to method
var newAId = getMRF_No("A");
var newAnotherAId = getMRF_No("A");
var newBId = getMRF_No("B");
var newAnotherAId2 = getMRF_No("A");
Console.ReadKey();
}

select all from access and place in string

I'm having trouble selecting all items from my access database. I want to select the data in the entire row and keep it in a string, separating each item by a ";". Below is the code i have that will give me the column i specify, but i want all the data in the row.
con.Open();
type= checkBox49.Text;
String str = "Select * from distro where type='" + type + "'";
cmd = new OleDbCommand(str, con);
dr = cmd.ExecuteReader();
if (dr.Read())
{
str2 = dr.GetString(1);
}
You can try something like this where columnsCount is the number of your columns in your database table
if (dr.Read())
{
for (int i = 0; i <columnsCount; i++)
{
str2 += string.Join(";",sdr.GetString(i));
}
}
You could select each field by name and combine them together like
str2 = dr["FieldName"].ToString() + "." + dr["FieldName"].ToString();
Also, I wouldn't reference any fields by number, but by FieldName.
So one approach, with the current code, would be this:
StringBuilder sb = new StringBuilder();
if (dr.Read())
{
for (int i = 0; i < dr.FieldCount; i++)
{
if (sb.Length > 0) { sb.Append(";"); }
sb.Append(dr.GetString(i));
}
}
A more global code if all your columns are not string type :
var con = new OleDbConnection();
var cmd = new OleDbCommand(str, con);
var dr = cmd.ExecuteReader();
var res = string.Empty;
if (dr.Read())
{
object[] t = new Object[dr.FieldCount];
if (dr.GetValues(t)>0)
{
res = String.Join(";", (from el in t select el as string).Where(x => x!=null).ToArray());
}
}
return res;
You could just string.Join all the values together.
con.Open();
type = checkBox49.Text;
String str = "Select * from distro where type=?";
cmd = new OleDbCommand(str, con);
cmd.Parameters.Add(type);
using (dr = cmd.ExecuteReader())
{
if (dr.Read())
{
var values = new object[dr.FieldCount];
dr.GetValues(values);
str2 = string.Join(";", values.Skip(1).Select(d => d.ToString());
}
}
Notice the use of a parameter in the query too. Standard way to avoid SQL Injection.

How to retrieve all fields for a given record using OracleDataReader?

My question, which is similar to this one, is how can I use OracleDataReader to retrieve all the fields for a given record? Currently, I've been using this method, which returns only one column value at a time:
public string Select_File(string filename, string subdirectory, string envID)
{
Data_Access da = new Data_Access();
OracleConnection conn = da.openDB();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT * FROM EIP_Deployment_Files"
+ " WHERE Filename ='" + filename + "'"
+ " AND Subdirectory = '" + subdirectory + "'"
+ " AND Environment_ID = '" + envID + "'";
cmd.CommandType = CommandType.Text;
string x;
OracleDataReader dr = cmd.ExecuteReader();
if (dr.HasRows) // file exists in DB
{
dr.Read();
x = dr.GetString(2).ToString(); // return baseline filename (index 2)
}
else
{
x = "New File";
}
cmd.Dispose();
da.CloseDB(conn);
return x;
}
I'm sure that this method is far from perfect and ppl will be quick to point that out (I was basically given it by my supervisor since I didn't have any prior experience in ASP.NET) but all I really care about is that it works. My question is: how can it be modified to return all the fields for a given record?
The fields will be of either VARCHAR2, CHAR, or DATE datatypes, (if that makes a difference) and some of these values may be null. I'm thinking I could convert them to strings and return them as a list?
if u want something like this:
List<User> lstUser = new List<User>();
string sqlQuery = "Select * from User_T where User_Name='" + oUser.UserName + "' And Password='" +oUser.Password + "' AND IsActive='"+1+"' AND IsDelete='"+0+"'";
string connectionString = "Data Source=ORCL;User Id=ACCOUNTS;Password=ACCOUNTS";
using (DBManager dbManager = new DBManager(connectionString))
{
try
{
dbManager.Open();
OracleDataReader dataReader = dbManager.ExecuteDataReader(sqlQuery);
while (dataReader.Read())
{
oUser = new User();
oUser.Id = Convert.ToInt32(dataReader["ID"]);
oUser.CompanyId = Convert.ToInt32(dataReader["Company_ID"]);
oUser.BranchId = Convert.ToInt32(dataReader["Branch_ID"]);
oUser.UserName = Convert.ToString(dataReader["User_Name"]);
lstUser.Add(oUser);
}
dataReader.Close();
dataReader.Dispose();
}
catch
(Exception)
{
}
finally
{
dbManager.Close();
dbManager.Dispose();
}
To read all the data from the columns of the current row in a DataReader, you can simply use GetValues(), and extract the values from the array - they will be Objects, of database types.
Object[] values;
int numColumns = dr.GetValues(values); //after "reading" a row
for (int i = 0; i < numColumns; i++) {
//read values[i]
}
MSDN - "For most applications, the GetValues method provides an efficient means for retrieving all columns, rather than retrieving each column individually."
Sorry for posting an answer to a very old question. As none of the answers are correct (either they have security issues or not checking for DBNull), I have decided to post my own.
public async Task<StringBuilder> FetchFileDetailsAsync(string filename, string subdirectory, string envId)
{
var sb = new StringBuilder();
//TODO: Check the parameters
const string connectionString = "user id=userid;password=secret;data source=" +
"(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=10.0.0.8)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=xe)))";
const string selectQuery = "SELECT * FROM EIP_Deployment_Files"
+ " WHERE Filename = :filename"
+ " AND Subdirectory = :subdirectory"
+ " AND Environment_ID = :envID"
+ " AND rownum<=1";
using (var connection = new OracleConnection(connectionString))
using (var cmd = new OracleCommand(selectQuery, connection) {BindByName = true, FetchSize = 1 /*As we are expecting only one record*/})
{
cmd.Parameters.Add(":filename", OracleDbType.Varchar2).Value = filename;
cmd.Parameters.Add(":subdirectory", OracleDbType.Varchar2).Value = subdirectory;
cmd.Parameters.Add(":envID", OracleDbType.Varchar2).Value = envId;
//TODO: Add Exception Handling
await connection.OpenAsync();
var dataReader = await cmd.ExecuteReaderAsync(CommandBehavior.CloseConnection);
var rowValues = new object[dataReader.FieldCount];
if (dataReader.Read())
{
dataReader.GetValues(rowValues);
for (var keyValueCounter = 0; keyValueCounter < rowValues.Length; keyValueCounter++)
{
sb.AppendFormat("{0}:{1}", dataReader.GetName(keyValueCounter),
rowValues[keyValueCounter] is DBNull ? string.Empty : rowValues[keyValueCounter])
.AppendLine();
}
}
else
{
//No records found, do something here
}
dataReader.Close();
dataReader.Dispose();
}
return sb;
}

Categories

Resources