Select multiple values with same ID - c#

Hi i am not sure how to retrieve all values with same id and display them in one label.
Example :
id food
1 chicken
1 fish
Desired output:
chicken,fish
How can i do that?
SqlConnection con1 = new SqlConnection(strConnString);
con.Open();
str = "select food from foodName where id= 1";
com = new SqlCommand(str, con);
SqlDataReader reader = com.ExecuteReader();
while (reader.Read())
{
Label1.Text = reader["food"].ToString();
}
con.Close();

Label1.Text = string.Empty;
SqlConnection con1 = new SqlConnection(strConnString);
con.Open();
str = "select food from foodName where id= 1";
com = new SqlCommand(str, con);
SqlDataReader reader = com.ExecuteReader();
while (reader.Read())
{
Label1.Text += reader["food"].ToString();
}
con.Close();

You can just do a foreach and add form a string using StringBuilder,
StringBuilder test = new StringBuilder();
foreach(yourClassname test in yourList)
{
test.Append(test.name);
}

Use lambda expression in C#.
var list = new List<Product>(){
new Product {ID=1, FoodName ="chicken"},
new Product{ID=2, FoodName="egg"},
new Product{ID=1, FoodName="fish"}
};
var output = list.Where(s => s.ID == 1).Select(s=>s.FoodName).ToArray(); //result will be array of items.
Use string.Join to get output results "chicken,fish"
string.Join(",", output); //result will be chicken,fish

Since you can't provide us your code. I'm assuming you have a list of food [List<Food>] and you have an id and foodName inside of it. What you can do is this:
IEnumerable<string> selectedFood = foods.FindAll(food => food.id == 1).Select(food => food.foodName);
string result = string.Join(", ", selectedFood);
You can now use the result as your label's value.
Hope this helps!

If you need to concatenate all values:
String chickenVar = "Chicken";
String fishVar = "Fish";
String result = chickenVar +", " + fishVar;

Related

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();
}

Add string array to SQL query

I have a string array which consists of identifiers. I want to get some values from SQL using these identifiers . Is there a way of adding them with a string value to SqlCommand parameters?
I want to create a query like:
select CaseList from MasterReportData where Id = 1 OR Id = 2 OR Id = 3
This is my C# code:
public static List<string> GetCaseList(string[] masterIdList)
{
try
{
string query = " select CaseList from MasterReportData where #masterId";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.AddWithValue("masterId", ***);
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
list.Add(reader[0].ToString());
}
}
conn.Close();
}
catch (Exception e)
{
var err= 0;
}
return list;
}
There are many different ways you can go about doing this but I prefer to create a temp table of possible values. That way you can do something like
select CaseList from MasterReportData where Id IN(select Id from tempTable)
The best approach (with sql optimization) would be:
Create your Type:
CREATE TYPE dbo.IntTTV AS TABLE
( Id int )
Your Ids:
var ids = new List<int>
{
1,
2,
3,
}
Create a schema:
var tableSchema = new List<SqlMetaData>(1)
{
new SqlMetaData("Id", SqlDbType.Int) // I think it's Int
}.ToArray();
Create the table in C#
var table = ids
.Select(i =>
{
var row = new SqlDataRecord(tableSchema);
row.SetInt32(0, i);
return row;
})
.ToList();
Create the SQL Parameter
var parameter = new SqlParameter();
parameter.SqlDbType = SqlDbType.Structured;
parameter.ParameterName = "#Ids";
parameter.Value = table;
parameter.TypeName = "dbo.IntTTV";
var parameters = new SqlParameter[1]
{
parameter
};
Slightly change your query (this is just an example:)
string query = "select mrd.CaseList from MasterReportData mrd"
+ " inner join #ids i on mrd.Id = i.id";
public static List<string> GetCaseList(string[] masterIdList)
{
List<string> list = new List<string>();
try
{
string query = "select CaseList from MasterReportData where ";
using (SqlConnection conn = new SqlConnection(connString))
{
int i = 0;
SqlCommand cmd = new SqlCommand(query, conn);
for(i = 0; i < masterIdList.Length; i++)
{
var parm = "#ID" + i;
cmd.Parameters.Add(new SqlParameter(parm, masterIdList[i]));
query += (i > 0 ? " OR " : "") + " Id = " + parm;
}
cmd.CommandText = query;
//cmd.Parameters.AddWithValue("masterId", ***);
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
list.Add(reader[0].ToString());
}
}
}
}
catch (Exception e)
{
e.ToString();
}
return list;
}

Auto increment ID with string

I'm using Access 2000-2003 database for C#. I like to have my TypeID to have a unique id as CHHTP001, CHHTP002 and etc, and display the id in TextBox before inserting new value in the database.
public void generateRateID()
{
string id;
con.Open();
string rate = "SELECT MAX(TypeID) FROM tblRoomTypeRate";
cmd = new OleDbCommand(rate, con);
OleDbDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
id = dr[0].ToString();
id = id + 1;
txtRateID.Text = "CHHRT" + id.PadLeft(3, '0');
}
con.Close();
}
The display in TextBox is CHHTP001 at first, then CHHTPCHHTP0011. How can I make the CHHTPCHHTP0011 to CHHTP002 and so on?
Use Regex. This should works as you want:
id = dr[0].ToString();//CHHTP001 Or CHHTP111
id = Regex.Replace(id, "\\d+", m => (int.Parse(m.Value) + 1).ToString(new string('0', m.Value.Length)));
txtRateID.Text = id;//CHHTP002 Or CHHTP112
Here is some general guidelines.
You should create an int variable that records what should be the number. That way you can manage your id easily. When you want to increment your id, just increment the variable.
When you want to convert the id to a string, first call ToString and PadLeft. Next you just concatenate the string to "CHHTP"! Isn't that easy?
Try this:
{
string id;
string literal; // "CHHRT" or whatever;
int sequence;
con.Open();
string rate = "SELECT MAX(TypeID) FROM tblRoomTypeRate";
cmd = new OleDbCommand(rate, con);
OleDbDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
id = dr[0].ToString();
sequence = int.Parse( new string( id.Where( char.IsDigit ).ToArray() ) );
literal = new string( id.Where( char.IsLetter ).ToArray() );
id = literal + ( sequence + 1 ).ToString( "000" );
txtRateID.Text = id;
}
con.Close();
}

Target a label whos ID is structured as "lblx1" by doing lblx + variable

I have a few labels on my site, which i need to populate with specific values from a database. So I've used a naming convention such as "lblx1", "lblx2", "lblx3" etc. and planned to do the following in a while loop:
lblx + id.Text = dbVariable
but this can't work as the code needs the name of an existing label in full.
public void beanList()
{
SqlCommand comm = new SqlCommand("SELECT id,Price250g,Price1kg FROM Beans", conn);
conn.Open();
SqlDataReader reader = comm.ExecuteReader();
while (reader.Read())
{
string id = reader["id"].ToString();
string price250g = reader["Price250g"].ToString();
string price1kg = reader["Price1kg"].ToString();
lbl250 + id.Text = price250g;
lbl1 + id.Text = price1kg;
}
}
I have also attempted from an anwser:
public void beanList()
{
SqlCommand comm = new SqlCommand("SELECT id,Price250g,Price1kg FROM Beans", conn);
conn.Open();
SqlDataReader reader = comm.ExecuteReader();
while (reader.Read())
{
string id = reader["id"].ToString();
string price250g = reader["Price250g"].ToString();
string price1kg = reader["Price1kg"].ToString();
Label l250g = new Label();
l250g.ID = "lbl250" + id;
l250g.Text = price250g;
Label l1kg = new Label();
l1kg.ID = "lbl1" + id;
l1kg.Text = price1kg;
}
}
But this does nothing, when stepping through "l250g.ID" is set, but "l250g.Text" doesn't work. It runs but is setting the text of the label whos ID it has been given.
Is there a way to get this to work without having to do a separate database query for each label, as the attempted while loop method is ideal as it would be fastest instead of calling the query X amount of times.
Create a List<string, Label>, like this:
List<KeyValuePair<string, Label>> elements = new List<KeyValuePair<string, Label>>();
Whenever you add an element, you do this:
elements.Add(new KeyValuePair<string, label>("lblx" + ids.Count, myLabel));
basically you need to find the control first. Hope the below code hint helps
string[] id = new string(1);
id[0] = reader["id"].ToString();
string price250g = reader["Price250g"].ToString();
string price1kg = reader["Price1kg"].ToString();
string templabel = null;
foreach (string i in id)
{
templabel = lbx + i;
var matches = this.Controls.Find(templabel, true).GetValue(0);
((Label)matches).Text = price250g;
}
I have specified GetValue(0) for my test. You can take a counter in your case.

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.

Categories

Resources