String combination does not work [closed] - c#

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Settings: asp.net mvc web app, azure sql db, EF code-first project
I am trying to combine 3 strings and a short into one string as given below:
CompanyAddress = company.ZipCode.ToString() + " " + company.City + ", " + company.Street + " " + company.StreetNr
ZipCode is a short, all others are strings. Using this code in a controller action returns no records (and no error message when run). When I omit the ZipCode part I get all records.
I also have tried ToString(company.ZipCode) and without .ToString(). Gives a wiggle-line (does not compile) and when run no error message and no records in return, respectively.
Please help.
Additional info:
The code line is part of an api controller (see below), ZipCode is nullable.
When ZipCode is part of the code line, then the controller delivers null, otherwise it delivers a proper string.
var companies = UnitOfWork.GetAll<Company>();
var query = company in companies
where company.Activ == true
select new ActiveCompaniesViewModel
{
CompanyAddress = company.ZipCode.ToString() + " " + company.City + ", " + company.Street + " " + company.StreetNr
};
return query;

This has been answered before,
Problem with converting int to string in Linq to entities
I think this will be your solution,
select new ActiveCompaniesViewModel
{
CompanyAddress = (company.ZipCode == null ? "" : SqlFunctions.StringConvert((int)company.ZipCode) + " ") +
company.City + ", " +
company.Street + " " +
company.StreetNr
};

That worked (does not make sense to me though!):
CompanyAddress = SqlFunctions.StringConvert((decimal?)company.ZipCode) + " " + company.City + ", " +
company.Street + " " +
company.StreetNr,

Related

How to declare a result into a string with proper format using variables? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I can't seem to wrap my head around the feedback on my code.
No result variable used. Use this variable to store your message + vacation type + group size.
I'm still new at learning the terms so when I worked on this assignment I was more focused on getting the result than understanding certain requirements. As the title suggests, I'm trying to figure out how to declare my result as a string.
How can I achieve that with correct sentence formatting using variables?
Here is my code for reference
public static void Main(string[] args)
{
Console.Write("What kind of trip would you like to go on, musical, tropical,"
+ "or adventurous?");
string vacationType = Console.ReadLine();
Console.Write("How many are in your group? ");
int groupSize = int.Parse(Console.ReadLine());
string vacationDest = "";
string travelSugg = "";
switch (vacationType)
{
case "tropical":
vacationDest = "a beach vacation in Mexico";
break;
case "musical":
vacationDest = "New Orleans";
break;
case "adventurous":
vacationDest = "white water rafting the Grand Canyon";
break;
}
if (groupSize <= 2)
travelSugg = "first class";
else if (groupSize > 2 && groupSize < 6)
travelSugg = "helicopter";
else
travelSugg = "charter flight";
Console.WriteLine("Since youre a group of " + groupSize
+ " going on a " + vacationType + " vacation, you should take a "
+ travelSugg + " to " + vacationDest);
Console.ReadLine();
}
Basically, instead of
Console.WriteLine("Since youre a group of " + groupSize
+ " going on a " + vacationType + " vacation, you should take a "
+ travelSugg + " to " + vacationDest );
you can do
var resultString = "Since youre a group of " + groupSize
+ " going on a " + vacationType + " vacation, you should take a "
+ travelSugg + " to " + vacationDest;
Console.WriteLine(resultString);
A proper way to insert values into a string variable is to use String.Format(). As you can see in the code below, it is easier to read. What you are doing is first building your sentence with curved brackets and numbers for positioning and then formatting that sentence with the values you want to add into your sentence.
string sentence = "Since you're a group of {0} going on a {1} vacation, you should take a {2} to {3}";
string output = string.Format(sentence, groupSize, vacationType, travelSugg, vacationDest);
Console.WriteLine(output);
Another solution I can provide to you is this one, which I think is the easiest to manipulate. In this one, you can literally just add the variable names you need at the position needed directly in the sentence.
Note that you need to add the dollar sign before the string $"" to allow you to write variables in it.
string sentence = $"Since you're a group of {groupSize} going on a {vacationType} vacation, you should take a {travelSugg} to {vacationDest}";
Console.WriteLine(sentence);
I recommend that you name your variables the best way possible without exagerating so that others can understand in a blink of an eye what is this variable containing. When using the second format solution, it would be easier to read something more like ... you should take a {travelSuggestion} to {travelDestination} don't you think?
To know more about the String.Format() method, I am referring you to the docs provided by Microsoft. I'm sure you will find it interesting.

QueryString is taking first substring and discarding rest post space

I have a query string which passes 6 parameters in C# as shown below
string url = "Report.aspx?Desc=" + Desc.SelectedValue + "&PON=" + PNumber.Text + "&InsNme=" + ins.ToUpper().ToString() + "&BackTy=" + cb.SelectedValue + "&StartDate=" + txtDate.Text + "&EndDate=" + txtTodate.Text + "&Name=" + nme;
string s = "window.open('" + url + "', 'popup_window', 'width=1500,height=800,left=200,top=150,resizable=yes');";
ClientScript.RegisterStartupScript(this.GetType(), "script", s, true);
Now, in the above string InsNme contains a value of John Patrice Joanne. Instead of complete value of InsNme Report.aspx contains just John. How to handle this?
The spaces in the name are breaking the URL.
If you want to do it yourself, replace spaces with %20. Otherwise a simple, but not anywhere near "good" technique is:
url = "Report.aspx?";
// for each name value pair ...
url += dataLabel + "=" + System.Web.HttpUtility.UrlEncode( dataChunk ) +"&";
The utility is preferred as it will take care of other, similar issues such as literal '&' in a name.
Check this answer for better solutions.
How to build a query string for a URL in C#?

open form on html button click in asp.net using C# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
will any body help me in opening a form on button click?? Thanks in advance.
aspx.cs Code:
public string wogrid()
{
string htmlStr = "";
con.COpen();
string qry = "SELECT id,casetype,Case when status_c=1 then 'Active' else 'Inactive' End as status_c FROM t_claimtype";
SqlDataReader rd = gd.DataReader(qry);
while (rd.Read())
{
int ID = Convert.ToInt16(rd["id"].ToString());
string caseType = rd["casetype"].ToString();
string status = rd["status_c"].ToString();
htmlStr += "<tr><td>" + ID + "</td>" + "<td>" + caseType + "</td>" + "<td>" + status + "</td>" + "<td>" + "<input type='submit' id='" + (rd)["ID"].ToString() + "' name='edit' value='EDIT' **onclick='windows.open(viewClaims.aspx)'** runat='server' />" + "</td></tr>";
}
con.cClose();
return htmlStr;
}
private void AddPlanToCart()
{
Response.Redirect("viewClaims.aspx");
}
This results in invalid JavaScript:
onclick='windows.open(viewClaims.aspx)'
Because:
There is no windows object, it's called window.
You didn't enclose the string "viewClaims.aspx" in quotes.
Additionally, HTML attributes should be enclosed in double-quotes. JavaScript strings can be single-quoted or double-quoted, so you have flexibility there. In order to do this on your current line of code you will need to "escape" some of the quotes. (This should be expected any time you try to mix three different languages on one line of code.)
Also additionally, this <input/> element should not include runat="server" because it's not a server-side control. That attribute wouldn't mean anything to a web browser and would just be ignored.
(Also remove those * characters. I'm sure they were there in an attempt to highlight that part of the code here in your post, but effectively they are invalid code and should be removed.)
Putting this together, this string literal that you currently have:
"' name='edit' value='EDIT' **onclick='windows.open(viewClaims.aspx)'** runat='server' />"
would become this:
"' name=\"edit\" value=\"EDIT\" onclick=\"windows.open('viewClaims.aspx')\" />"
Semantically your really shouldn't be using a button at all for this in the first place. The functionality you're building is to direct the user to another page when they click on something. A link already does that. And it does it by default without the need for JavaScript or trying to get around the use of a form or any other hacks.
Just use a link:
"Edit"

How to deal with null values in C# from Access DB? [duplicate]

This question already has answers here:
Removing extra commas from string after using String.Join to convert array to string (C#)
(9 answers)
Closed 8 years ago.
In my C# form I have address field in that i need to fill address that already DoorNo, Street, Area, Location are stored separately in Access Database. I used string concatenation to merge full address.
object row = CBL_Customer_Name.Properties.GetDataSourceRowByKeyValue(CBL_Customer_Name.EditValue) as object;
string getblocation = (row as DataRowView)["BLocation"].ToString();
string getbcity = (row as DataRowView)["BCity"].ToString();
string getbstate = (row as DataRowView)["BState"].ToString();
string getbcountry = (row as DataRowView)["BCountry"].ToString();
TXE_Invoice_Address.Text = (row as DataRowView)["BFlatNo"].ToString() + ", " + (row as DataRowView)["BPremises"].ToString() + "," + System.Environment.NewLine + (row as DataRowView)["BStreet"].ToString() + ", " + getloction(getblocation) + "," + System.Environment.NewLine + (row as DataRowView)["BArea"].ToString() + ", " + getcity(getbcity) + "," + System.Environment.NewLine + getstate(getbstate) + ", " + getcountry(getbcountry) + ".";
If user enter complete address then no problem in this above code. If he doesn't enter location or some other fields then am getting , , or blank space in the end of line.
How to solve this ? I need a perfect address in my address field if user leave 1 or 2 fields also.
Use .replace() to replace empty values by a custom text.
Example
TXE_Invoice_Address.Text = TXE_Invoice_Address.Text.Replace(", ,", ", ")
This code will remove all , , that may cause a strange adress format.
Try this: var newAddress = string.Join(", ",TXE_Invoice_Address.Text.Split(',').Where(x => !string.IsNullOrWhiteSpace(x)));
This will eliminate all empty spaces and rejoin to new a string.

Remove specific string from given URL

I have a URL example image1-resize.jpg, and I want to delete -resize and save image1.jpg in new variable.
How can I do that?
This is what I tried to do:
str1 += "<li><a href='#pic" + counter + "'><img src='admin/temp/hotelimg/" + temp_url.ToString() + "'/></a></li>";
string stt =temp_url.replace("-resize","");
str2 += "<div id='pic" + counter + "'><img src='admin/temp/hotelimg/" + stt.ToString() + "' width='550' height='370'/></div>";
This should do your job:
temp_url.replace("-resize","");
Note: You should always search before putting questions here, since sometimes its really easy and need just small research on it.

Categories

Resources