SqlDataReader: Combine Records in One String with Delimeters - sqldatareader

I would like to combine 2 or more records in a single string based from SqlDataReader data.
SqlDataReader data = cmd.ExecuteReader();
string category = "";
while (data.Read())
{
category = data["Column1"].ToString() + ", " + category;
}
ltCategory.Text = category.TrimEnd(',');
I have 2 existing records and the ltCategory.Text displays Record1, Record2,
I want to use the following format:
Record1
Record1, Record2, Record3
SOLUTION
SqlDataReader data = cmd.ExecuteReader();
string category = "";
while (data.Read())
{
category += ", " + data["Column1"].ToString();
}
ltCategory.Text = category.TrimStart(',');

Change category = data["Column1"].ToString() + ", " + category; to category += data["Column1"].ToString() + ", ";
ltCategory.Text = category.TrimEnd(',');
This might need to be changed as well to:
ltCategory.Text = category.TrimEnd(', ');

Related

Upload and update excel file

I have a task to upload the excel file and also check update if the same record found, I have uploaded the excel file in the database which is working fine.
Now, I have to check if the same records inserted then update otherwise insert the new records, I have two table first I am inserting the records in the temp table then after that I am checking the temp table with the original table , if records matches then update else insert, I am using nested for loop to check the records
my loop works fine and insert the top two records, but when it comes to the 3rd record then insert it multiple times and on 4th again multiple times,Kindly guide me what i am doing wrong
here is my code so far
protected void btnUpload_Click(object sender, EventArgs e)
{
try
{
int id;
string contactPerson;
string designation;
string company;
string contact;
string emailaddress;
string city;
string region;
string industry;
string division;
string mobile;
string address;
string path = Path.GetFileName(FileUpload1.FileName);
path = path.Replace(" ", "");
FileUpload1.SaveAs(Server.MapPath("~/uploadExcel/") + FileUpload1.FileName);
String ExcelPath = Server.MapPath("~/uploadExcel/") + FileUpload1.FileName;
OleDbConnection mycon = new OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0; Data Source = " + ExcelPath + "; Extended Properties=Excel 8.0; Persist Security Info = False");
mycon.Open();
DeleteRecords();
OleDbCommand cmd = new OleDbCommand("select * from [Sheet1$]", mycon);
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr[0].ToString() != "")
{
// Response.Write("<br/>"+dr[0].ToString());
id = Convert.ToInt32(dr[0].ToString());
contactPerson = dr[1].ToString();
designation = dr[2].ToString();
company = dr[3].ToString();
emailaddress = dr[4].ToString();
contact = dr[5].ToString();
mobile = dr[6].ToString();
address = dr[7].ToString();
city = dr[8].ToString();
region = dr[9].ToString();
industry = dr[10].ToString();
division = dr[11].ToString();
InsertTemp(id, contactPerson, designation, company, emailaddress, contact,
mobile, address, city, region, industry, division);
//InsertOrignal(id, contactPerson, designation, company, emailaddress, contact,
// mobile, address, city, region, industry, division);
}
else
{
break;
}
String myconn = "Data Source=Ali-PC;Initial Catalog=MushkhoApp;Integrated Security=True";
SqlConnection conn = new SqlConnection(myconn);
conn.Open();
DataTable dt_temp = new DataTable();
DataTable dt_orignal = new DataTable();
SqlDataAdapter da_temp = new SqlDataAdapter("select * from Tbl_ExcelData order by id asc", conn);
SqlDataAdapter da_orignal = new SqlDataAdapter("select * from Tbl_ExcelUploadData order by id asc", conn);
da_temp.Fill(dt_temp);
da_orignal.Fill(dt_orignal);
if (dt_orignal.Rows.Count > 0)
{
for (int i = 0; i < dt_temp.Rows.Count; i++)
{
for (int j = 0; j < dt_orignal.Rows.Count; j++)
{
if (dt_temp.Rows[i]["email"].ToString() == dt_orignal.Rows[j]["email"].ToString())
{
//Update Record if required
}
else
{
//insert record into orignal table
InsertOrignal(id, contactPerson, designation, company, emailaddress, contact, mobile, address, city, region, industry, division);
}
}
}
}
else
{
InsertOrignal(id, contactPerson, designation, company, emailaddress, contact, mobile, address, city, region, industry, division);
}
}
lblmessage.Text = "Data Has Been Updated Successfully";
mycon.Close();
File.Delete(ExcelPath);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private void InsertTemp(int id, String contactPerson, String designation, String company, String emailaddress,
String contact, String mobile, String address,String city,String region,String industry,
String division)
{
//String mycon = "Data Source=Ali-PC;Initial Catalog=MushkhoApp;Integrated Security=True";
SqlConnection con = new SqlConnection(mycon);
con.Open();
string query = "insert into Tbl_ExcelData (id,contactperson,designation,company,email,contact,mobile,address,city,region,industry,division) values('" + id + "','" + contactPerson + "', '" + designation + "','" + company + "','" + emailaddress + "','" + contact + "','" + mobile + "','" + address + "','" + city + "','" + region + "','" + industry + "','" + division + "')";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = query;
cmd.Connection = con;
cmd.ExecuteNonQuery();
}
private void InsertOrignal(int id, String contactPerson, String designation, String company, String emailaddress,
String contact, String mobile, String address, String city, String region, String industry,
String division)
{
//String mycon = "Data Source=Ali-PC;Initial Catalog=MushkhoApp;Integrated Security=True";
SqlConnection con = new SqlConnection(mycon);
con.Open();
string query = "insert into Tbl_ExcelUploadData (id,contactperson,designation,company,email,contact,mobile,address,city,region,industry,division) values('" + id + "','" + contactPerson + "', '" + designation + "','" + company + "','" + emailaddress + "','" + contact + "','" + mobile + "','" + address + "','" + city + "','" + region + "','" + industry + "','" + division + "')";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = query;
cmd.Connection = con;
cmd.ExecuteNonQuery();
}
private void DeleteRecords()
{
SqlConnection con = new SqlConnection(mycon);
con.Open();
string query = "Delete from Tbl_ExcelData";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = query;
cmd.Connection = con;
cmd.ExecuteNonQuery();
}
}
If you have the Temporary table just to check if the row exists in an Original table, then it is not a good practice.
Directly check if the row exists in your original table with the Primary key id or any Unique Key and then decide whether to Insert or Update.
One way to do this,
while (dr.Read())
{
if (dr[0].ToString() != "")
{
id = Convert.ToInt32(dr[0].ToString()); //add other columns which needs to be fetched from Excel
string query = "select count(1) from Tbl_ExcelData where id=?"; //To check if the row already exsits
SqlCommand cmd = new SqlCommand(con);
cmd.CommandText = query;
cmd.Paramaters.Add(new SqlParameter(1, id));
int count = (Int32) cmd.ExecuteScalar();
if (count > 0) //which means row already exists
{
//Your update code goes here
}
else
{
InsertOrignal(id, contactPerson, designation, company, emailaddress, contact, mobile, address, city, region, industry, division);
}
}
After comments, here is a basic idea. One way you can load your excel data into DataTable and loop through it and decide for Upsert. Remember to learn about MultipleActiveResultSets
try
{
string ExcelPath = Server.MapPath("~/uploadExcel/") + FileUpload1.FileName;
string _oleDBConnectionString = string.Format("Provider = Microsoft.ACE.OLEDB.12.0; Data Source = {0}; Extended Properties=Excel 8.0; Persist Security Info = False", ExcelPath);
string _sqlConnectionString = "Data Source=Ali-PC;Initial Catalog=MushkhoApp;Integrated Security=True; MultipleActiveResultSets=true;"; //enable MultipleActiveResultSets as you'll be opening a nested SqlConnection
string _excelQuery = "select * from [Sheet1$]";
DataTable tempDataTable = null;
using (var conn = new OleDbConnection(_oleDBConnectionString)) //This code loads your excel data into data table
{
conn.Open();
using (var cmd = new OleDbCommand(_excelQuery, conn))
{
using (var reader = cmd.ExecuteReader())
{
var dt = new DataTable();
dt.Load(reader); //this will load your excel data into DataTable
tempDataTable = dt;
}
}
}
using(var sqlConn = new SqlConnection(_sqlConnectionString)) //this code will connect to sql db and upsert based on the id from the excel
{
sqlConn.Open();
string countQuery = "select count(1) from Tbl_ExcelData where id=:id";
using(var cmd = new SqlCommand(countQuery, sqlConn))
{
var param = new SqlParameter("#id");
foreach (DataRow row in tempDataTable.Rows) //this will loop through the DataTable rows, the actual rows from Excel which are loaded into DataTable
{
var id = row["id"]; //get the id column from the excel
var contactPerson = row["contactPerson"]; //get the contactPerson column from the excel
cmd.Paramaters["#id"] = id;
int count = (int) cmd.ExecuteScalar();
if (count) //row already exist in original table
{
//update the row in original table
}
else
{
//insert the row in original table
InsertOriginal(sqlConn, id, contactPerson);
}
}
}
}
}
catch(Exception ex)
{
}
function InsertOriginal(SqlConnection conn, int id, string contactPerson)
{
string insertQuery = "insert into Tbl_ExcelUploadData (id,contactpersonn) values('#id','#contactPerson');
using(var cmd = new SqlCommand(insertQuery, conn))
{
cmd.Parameters.Add(new SqlParameter("#id",id));
cmd.Parameters.Add(new SqlParameter("#contactPerson", contactPerson));
cmd.ExecuteNonQuery();
}
}
Also, this is not a tested code. Feel free to comment back.

Database value in label asp.net c#

I am trying to get value from database to be display in label. First i have to get the value of the dropdownlist and retrieved from database based on it. After that, I need to get the titlePromo column into my Label.
Currently i have the code out but i am not sure if it is the right one. There is no error but it displayed the membershipType column instead of the titlePromo.
ID titlePromo membershipType defaults
-- ---------- -------------- ------
1 Promo 1 Membership Promotion Y
2 Promo 2 Membership Renewal Y
3 Promo 3 Membership Grad Y
4 Promo 4 Membership Promotion N
5 Promo 5 Membership Promotion N
6 Promo 6 Membership Grad N
My codes that i have done so far:
string strConnectionString = ConfigurationManager.ConnectionStrings["FYPDB"].ConnectionString;
SqlConnection myConnect = new SqlConnection(strConnectionString);
string strCommandText2 = "select * FROM FYPDB.dbo.Promotions where membershipType = '%' + #membership + '%' AND defaults = 'Y'";
string ddlmembership = ((DropDownList)dvInsertPromotion.FindControl("ddlAddMembershiplist")).SelectedItem.ToString();
cmd.Parameters.Add("#membership", SqlDbType.NVarChar);
cmd.Parameters["#membership"].Value = ddlmembership;
DataSet da2 = dal.retrieveTitle(ddlmembership);
SqlCommand cmd2 = new SqlCommand(strCommandText2, myConnect);
((Label)pnlDefaultPopup.FindControl("Label13")).Visible = true;
((Label)pnlDefaultPopup.FindControl("Label13")).Text = da2.Tables[0].Rows[0]["titlePromo"].ToString();
html:
.cs
public DataSet retrieveTitle(String membership)
{
SqlParameter[] parameters = new SqlParameter[]{
new SqlParameter("#membership", SqlDbType.NVarChar),
};
parameters[0].Value = membership;
DataSet ds = new DataSet();
ds = commons.ExecuteDataSet("Select * FROM Promotions WHERE (membershipType = '" + membership + "') AND defaults = 'Y' ");
return ds;
}
Before giving you my suggestion I would like to make some remarks to your existing code:
you should select only the titlePromo in your query, as you only need one field, and not the entire row (therefore you wouldn't need a dataset in the first place)
the naming of your function is not according to its scope, at it does not retrieve the title, but an entire entry in the promotions table.
in this structure "membershipType = '%' + #membership + '%'" the syntax is not correct. The wildcards are used together with the "like" keyword
Bellow, you can find my code sample of how would I implement it if I were you:
static void Main(string[] args)
{
using (SqlConnection PubsConn = new SqlConnection(yourConnectionString))
{
//code to retrieve membership
var membership = "Membership Promotion";
var title = retrieveTitle(PubsConn, membership);
//code to set up label
}
}
public static string retrieveTitle(SqlConnection conn, String membership)
{
conn.Open();
var title = string.Empty;
string strCommandText = "select top 1 titlePromo FROM Promotions where membershipType = #membership AND defaults = 'Y'";
SqlCommand commmand = new SqlCommand(strCommandText, conn);
commmand.Parameters.AddWithValue("#membership", membership);
try
{
using (SqlDataReader reader = commmand.ExecuteReader())
{
if (reader != null && reader.Read())
{
title = Convert.ToString(reader["titlePromo"]);
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error while retrieving table: " + ex.Message);
}
conn.Close();
return title;
}
If you want to use wildcards and 'like', you can do it like this:
string strCommandText = "select top 1 titlePromo FROM membershipTest where membershipType like #membership AND defaults = 'Y'";
SqlCommand commmand = new SqlCommand(strCommandText, conn);
commmand.Parameters.AddWithValue("#membership", "%" + membership + "%");

How to get a variable replaced with a field name in a LINQ?

string companyName="ABC";
var query = from q in context.Company where q.CompanyName == companyName select q;
Is there any way to replace the q.CompanyName part of the query with a string variable
so that the field used for filtering be a parametric?
I tried
string str1 = "companySize";
string str2 = "q." + str1;
string companySize = "Mid";
var query = from q in context.Company where str2 == companySize select q;
Didn't work.
Been trying to let the user choose the columns for the query.
Read more about both below option at : Dynamic query with Linq
you can use one of this
Use Dynamic LINQ library
Example for the the blog below
string strWhere = string.Empty;
string strOrderBy = string.Empty;
if (!string.IsNullOrEmpty(txtAddress.Text))
strWhere = "Address.StartsWith(\"" + txtAddress.Text + "\")";
if (!string.IsNullOrEmpty(txtEmpId.Text))
{
if(!string.IsNullOrEmpty(strWhere ))
strWhere = " And ";
strWhere = "Id = " + txtEmpId.Text;
}
if (!string.IsNullOrEmpty(txtDesc.Text))
{
if (!string.IsNullOrEmpty(strWhere))
strWhere = " And ";
strWhere = "Desc.StartsWith(\"" + txtDesc.Text + "\")";
}
if (!string.IsNullOrEmpty(txtName.Text))
{
if (!string.IsNullOrEmpty(strWhere))
strWhere = " And ";
strWhere = "Name.StartsWith(\"" + txtName.Text + "\")";
}
EmployeeDataContext edb = new EmployeeDataContext();
var emp = edb.Employees.Where(strWhere);
Predicate Builder
EXample
var predicate = PredicateBuilder.True<employee>();
if(!string.IsNullOrEmpty(txtAddress.Text))
predicate = predicate.And(e1 => e1.Address.Contains(txtAddress.Text));
if (!string.IsNullOrEmpty(txtEmpId.Text))
predicate = predicate.And(e1 => e1.Id == Convert.ToInt32(txtEmpId.Text));
if (!string.IsNullOrEmpty(txtDesc.Text))
predicate = predicate.And(e1 => e1.Desc.Contains(txtDesc.Text));
if (!string.IsNullOrEmpty(txtName.Text))
predicate = predicate.And(e1 => e1.Name.Contains(txtName.Text));
EmployeeDataContext edb= new EmployeeDataContext();
var emp = edb.Employees.Where(predicate);
If you don't want to use libraries like dynamicLINQ, you can just create the Expression Tree by yourself:
string str1 = "companySize";
string str2 = "q." + str1;
string companySize = "Mid";
var param = Expression.Parameter(typeof(string));
var exp = Expression.Lambda<Func<Company, bool>>(
Expression.Equal(
Expression.Property(param, str1),
Expression.Constant(companySize)),
param);
var query = context.Company.Where(exp);
I think the best way to do this is with built in libraries (and PropertyDescriptor type).
using System.ComponentModel;
void Main()
{
Test test = new Test();
test.CompanyName = "ABC";
object z = TypeDescriptor.GetProperties(test).OfType<PropertyDescriptor>()
.Where(x => x.Name == "CompanyName").Select(x => x.GetValue(test)).FirstOrDefault();
Console.WriteLine(z.ToString());
}
public class Test
{
public string CompanyName { get; set; }
}

Input string was not in a correct format (ASP.NET)

string s1 = DropDownList1.SelectedItem.Text;
string s2 = DropDownList2.SelectedItem.Text;
string sql1 = ("Select Case_Type_Value FROM Case_Type where Case_Type_Text IS'" + s1 + "' ");
string sql2 = ("Select Case_Status_Value FROM Case_Status where Case_Status_Text IS'" + s2 + "' ");
int v1 = Int32.Parse(sql1);
int v2 = Int32.Parse(sql2);
Hi
I am getting error "Input string was not in a correct format" on line:
int v1 = Int32.Parse(sql1);
Of course you are getting an error!
See you are not fetching result from database. Instead you are assigning your query to sql1 and trying to convert it into integer. See below in your code you are actually assigning whole select query to the string sql1.You can try this one :
string sql1 = ("Select Case_Type_Value FROM Case_Type where Case_Type_Text IS'" + s1 + "' ");
string sql2 = ("Select Case_Status_Value FROM Case_Status where Case_Status_Text IS'" + s2 + "' ");
sqlconnection con = new SqlConnection("Blah Blah")
Sqlcommand cmd = new sqlcommand(sql1,con);
con.open();
int v1 = Convert.toint32(cmd.ExecuteScalar());
con.close();
con.Dispose();
Which type you receive when you
string sql1 = ("Select Case_Type_Value FROM Case_Type where Case_Type_Text IS'" + s1 + "' ");
string sql2 = ("Select Case_Status_Value FROM Case_Status where Case_Status_Text IS'" + s2 + "' ");
?
you can do one thing just take column called Group like you have taken in the Usertype.
Take a session variable and capture username in it.Then get the group to which the username belongs. Based on the role redirect the user to his corresponding page.
Session["unmae"]=txtuname.text;
string username=Session["unmae"].Text;
string group=obj.getgroup(username);
if(group=="Admin")
{
Response.Redirect("1.aspx");
}
else if(group=="User")
{
Response.Redirect("2.aspx");
}
else
{
Response.Redirect("error.aspx");
}
Hope this helps.
Happy coding

Incorrect syntax near ','. error

I am getting an SQL error when I try to do this:
public static int GetOrderId(decimal totalprice, int userid)
{
string s = "SELECT * from orders where OrderUserId = " + userid + " and OrderTotalPrice = " + totalprice;
cmd = new SqlCommand(s, con);
int temporderid = Convert.ToInt32(cmd.ExecuteScalar());
return temporderid;
}
As far I can see its because it gets OrderTotalPrice back, the format is incompatible. But I cant figure out how to get it in the compatible format.
It's probably formatting totalprice with a comma, like 3,14, where SQL Server expects a dot, like 3.14.
One way to fix that would be to specify InvariantCulture, which uses a dot:
var s = string.Format(
CultureInfo.InvariantCulture,
"SELECT * from orders where OrderUserId = {0} and OrderTotalPrice = {0:0.0}",
42, 3.1415);
This formats the price as 3.1 on any machine.
By the way, it's much nicer to pass the variables as parameters:
var com = new SqlCommand();
com.CommandType = CommandType.Text;
com.CommandText = "SELECT * from orders where OrderUserId = #userid " +
"and OrderTotalPrice = #totalprice";
com.Parameters.AddWithValue("#userid", 42);
com.Parameters.AddWithValue("#totalprice", 3.1415);
var temporderid = com.ExecuteScalar();
Then you don't have to worry about formats because you send the database a double, not a double formatted as a string.
I guess this is because totalprice gets converted to something like 12,35 when you concatenate the query.
Therefore, I'd suggest you use a parametrized query. E.g. like this:
var s = "SELECT * from orders " +
" where OrderUserId = #userid and OrderTotalPrice = #totalprice";
var cmd = new SqlCommand(s, con);
cmd.Parameters.AddWithValue("userid", userid);
cmd.Parameters.AddWithValue("totalprice", totalprice);
int temporderid = Convert.ToInt32(cmd.ExecuteScalar());

Resources