Setting an ID as an Integer with C# - c#

I am currently using the following script to set this value as a String:
string ID = Request.QueryString["ID"].ToString();
However, I'd now like to store it as an Integer.
How do I do this?
Many thanks for any pointers.

Assuming you don't want to throw a server error on a bad string
int id=0;
if (int.TryParse(Request.QueryString["ID"],out id)) {
.. logic for valid id
} else {
.. logic for invalid id
}

int ID = int.Parse(Request.QueryString["ID"].ToString());

Use either of these:
If you know that you have an ID:
string ID = Request.QueryString["ID"];
int integerId = int.Parse(ID);
or, if the query string may be missing or invalid (never trust query strings....)
string ID = Request.QueryString["ID"];
int integerId;
if (int.TryParse(ID, out integerId))
{
// you have a valid integer ID here.
// process it
}
else
{
// handle missing or invalid ID
}

You could do something like:
int i = Convert.ToInt32(ID);
or
int i;
Int32.TryParse(ID, out i);
BTW Request.QueryString["ID"] is already a string so the following is fine:
string ID = Request.QueryString["ID"];

Try
int ID = int.Parse(Request.QueryString["ID"]);
See How can I convert String to Int?

You can do like this:
string ID = Request.QueryString["ID"].ToString();
int id=int.Parse(ID);
or
int id=Convert.ToInt16(ID);

Always use tryparse for querystring values if you want to convert it to integer even if you never set it to string , because user can change that anytime before sending request (visible in URL).
int id = 0 ;//default value
bool success = int.TryParse(Request.QueryString["ID"],out id))
if (success) {
//write code for default value action
return;
}
//write code for other values.

Related

How to send a value from .aspx file to .cs file

I have made a link on the webpage like
<a href="Products.aspx?id='something'">
Now this send id to a page Products.aspx
I want this value of id in the Products.aspx.cs file of the page so that I can write a query like
select * from Categories Where CategoryID = 'something'
Try to use the following ,Below i mentioned get Querystring value in code behind.
string Id = string.Empty;
if (Request.QueryString["id"] != null)
{
Id = Request.QueryString["id"].ToString();
}
var query = " select* from Categories Where CategoryID = '" + Id + "'";
You can get id sent using Query String like below:
if(Request.QueryString["id"] != null)
{
string value = Request.QueryString["id"].ToString();
}
You have lots of way to pass id Form One Page to Another page Name
Products.aspx Or Products.aspx.cs
Ill Explain Two way
One is Session and Another is QueryString.
Session Examle.............
Session : Assign Value of ID on Page A
Session["id"]='something';
Get Value On Page Products.aspx
string Val=Session["id"].ToString();
Query String Examle.............
QueryString: Assign Value of ID on Page A
string DymanicURL = string.Format("Products.aspx?id={0}", Val);
Response.Redirect(DymanicURL);
Get Value On Page Products.aspx
string x = Request.QueryString["id"];
For More Info http://www.dotnetperls.com/querystring
and https://msdn.microsoft.com/en-us/library/6c3yckfw.aspx
you can get the ID value in the targeted products cs page using following syntax
string ID = Request.QueryString["id"].tostring();
You can get query string values as passed in the way you describe using
var categoryId = Request.QueryString["CategoryId"]
You'll want to check that it's not null or empty before proceeding, of course...
Try to use the following
string Qvalue="";
if(Request.QueryString["id"] != null) {
Qvalue = Request.QueryString["id"].ToString(); }
Your query should look likes this
select * from Categories Where CategoryID = '"+Qvalue+"'
if you would like to send id from one page to another CS page then you may use properties
class Person
{
private string name; // the name field
public string Name // the Name property
{
get
{
return name;
}
set
{
name = value;
}
}
}
On ASPX Page you may put value on properties like :
Person person = new Person();
person.Name = "Joe"; // the set accessor is invoked here
OR
person.Name = txt_Name.Text; // the set accessor is invoked here
after that get data On CS page.
System.Console.Write(person.Name); // the get accessor is invoked here
OR
string Value= person.Name; // the get accessor is invoked here

The best overloaded method match for... has some invalid arguments

I am using DataAdapter("SDM_Tran_GenerateInvoice") inside DataSet("SDMDAL.xsd") in my project.
Below is the structure of DataAdapter along with the Stored Procedure names in it:
Below is the Table structure Im using for the same:
I am calling this DataAdapter inside Class file named as SDM.InvoiceBLL.cs:
using SDMDALTableAdapters;
public class SDM_Invoice
{
private SDM_Tran_GenerateInvoiceTableAdapter _GenerateInvoiceTableAdapter = null;
protected SDM_Tran_GenerateInvoiceTableAdapter Adapter
{
get
{
if (_GenerateInvoiceTableAdapter == null)
_GenerateInvoiceTableAdapter = new SDM_Tran_GenerateInvoiceTableAdapter();
return _GenerateInvoiceTableAdapter;
}
}
#region GET
//to show data in Invoice Grid
public SDMDAL.SDM_Tran_GenerateInvoiceDataTable SelectInvoice(string _SPID)
{
return Adapter.SelectInvoice(_SPID);
}
//to show data in 1st hidden Grid
public SDMDAL.SDM_Tran_GenerateInvoiceDataTable GetInvoiceBillingBySPID(string _SPID)
{
return Adapter.GetInvoiceBillingBySPID(_SPID);
}
//to fetch InvoiceID for unique key generation
public SDMDAL.SDM_Tran_GenerateInvoiceDataTable GetInvoiceID()
{
return Adapter.GetInvoiceID();
}
//to fetch InvoiceNumber for unique key generation
public SDMDAL.SDM_Tran_GenerateInvoiceDataTable GetInvoiceNumber()
{
return Adapter.GetInvoiceNumber();
}
#endregion
public string Insert(string InvoiceID, string SPfoID, string InvoiceLineNo, string InvoiceNo, string InvoiceType, string BillingIDfoID, string BusinessUnit, string DirectCost, string InvfoStatusID, string Status, DateTime Date, string AccountCode)
{
string query = Convert.ToString(Adapter.Insert1(InvoiceNo, SPfoID, InvoiceLineNo, InvoiceNo, InvoiceType, BillingIDfoID, BusinessUnit, DirectCost, InvfoStatusID, Status, Date, AccountCode));
return query;
}
public SDM_Invoice()
{
}
}
and then calling the "Insert" function of class file inside Default.aspx.cs page, to save records on button click:
protected void btnInvoice_Click(object sender, EventArgs e)
{
generateInvoiceId();
generateInvoiceNumber();
string InvType = rlbInvType.SelectedValue;
string Status = "Draft";
string BillingID;
string DirectCost;
string BusinessUnit;
string StatusID;
string AccCode;
foreach (GridDataItem itm in rgData.Items)
{
BillingID = itm["BillingID"].Text;
DirectCost = itm["DCIDescription"].Text;
BusinessUnit = itm["BUName"].Text;
StatusID = itm["BUfoStatusID"].Text;
Label lb = (Label)itm.FindControl("Label1");
string InvLineNo = lb.Text;
try
{
SDM.Invoice.Insert(lblInvId.Text, _SPID, InvLineNo, lblInvNo, InvType, BillingID, BusinessUnit, DirectCost, StatusID, Status, DateTime.Now, AccCode);
}
catch (Exception ex)
{
}
}
}
I rebuilt my project number of times and when I run my web page "Default.aspx.cs", always it gives me below error:
The best overloaded method match for 'SDM_Invoice.Insert(string, string, string, string, string, string, string, string, string, string, System.DateTime, string)' has some invalid arguments
I searched many articles related to my issue but couldn't find any solution for my problem.
This is the first time I am working with TableAdapter. Please help me what is wrong in my code ? What am I missing in it. Thanks in advance.
All the arguments except for the next to last need to be strings, but you seem to be passing some non-string values, for example lblInvNo, which seems to be a user interface element.
Check the type of each argument aside from the next to last, and make sure they are all strings.

How can I select a number and value from an enum in C#?

I have just changed my code so that now it stores some data in an enum instead of in a SQL Server table.
Here's the enum:
public enum ContentTypes : int
{
Article = 0,
Menu = 1,
ContentBlock = 3
}
I was running the following code:
var contentTypes =
(
from contentType in this._contentTypeService.GetContentTypes()
select new
{
id = contentType.ContentTypeId,
name = contentType.Name
}
);
How can I change this so that instead of taking the data from the content service it just queries the enum to data for contentTypes?
I think what you want is this
var contentTypes =
from value in Enum.GetValues(typeof(ContentTypes)).Cast<int>()
select new
{
id = value,
name = Enum.GetName(typeof(ContentTypes), value)
};
pswg might be right, but I am thinking you want something like this?
Here is code more direct to your question:
select new
{
id = (int)contentType,
name = contentType.ToString()
}
You can get the integer id simply by casting to an int and get the name of it by using its ToString (which may or may not be implicit here)

C#: recursive search in two different data structures

I need to perform a search in two different data structures in C#, and here's the deal:
I have one name (which is a string) and I want to perform a search. I have a function called Exists which will return a bool indicating whether it exists or not.
In case it exists, I increase the name (simply adding a 1 at the end of the string), and then I need to perform the search again (via method exists) to see if an object with the new name exists.
This would go on until there's an unused name, which I could use, BUT, in case it doesn't exist, now I should perform a search another data structure which contains the objects that were deleted, and if the string is found there, then I'd have to increase the name again, and start searching since the beginning.
This would all end in case there's no object with such name neither using Exists method nor in the data structure where all the deleted objects are.
How could I approach this problem?
I hope I expressed myself clearly :-)
Thanks a lot in advance!
string BuildNextName(string originalName)
{
string name = originalName;
while( Exists(name) || deletedNames.Contains(name))
{
name = Increment(name);
}
return name;
}
Or did I miss something?
Using a for loop:
string BuildNextName(string originalName)
{
for (string name=originalName;
Exists(name) || deletedNames.Contains(name);
name = Increment(name));
return name;
}
BTW, I guess your name incrementation algorithm is more complex than simply adding 1: name, name1, name2,... Basically, if the name doesn't end in a number, you append "1". If it does, you increment that number. right?
a non recursive and simple solution could be something like this ( I don't see any need of recursion in this case)
//pseudocode
String name;
bool condition = true;
while(condition)
{
if(ExistInFirstDataStructure(name))
{
//increment name
}
else
{
if(ExistInDeletedDataStructure(String name))
{
//increment name
}
else
{
condition = false;
}
}
}
bool ExistInFirstDataStructure(String name)
{
}
bool ExistInDeletedDataStructure(String name)
{
}
Why use a loop at all?? (I know LINQ will under the hood)
var LastUsedObjectName =
MyObjects.Select(mo => mo.Name)
.Union( MyDeletedObjects.Select(mo => mo.Name))
.OrderByDescending(name => /*Function to order by integer part of name*/).First();
// Now add 1 to LastUseObjectName and use that.
How about this one:
var listOfExistingNames = new List<string> { "MyName", "MyName1", "MyName3" };
var listOfDeletedNames = new List<string> { "MyName2", "MyName5" };
int counter = 0;
string baseToFindFreePlace = "MyName";
string newName = baseToFindFreePlace;
var allNames = listOfExistingNames.Concat(listOfDeletedNames);
while (allNames.Contains(newName))
{
counter++;
newName = baseToFindFreePlace + counter;
}
listOfExistingNames.Add(newName);
if you create Exists methods for both data structures, you can search with recursion like this:
pseudo code:
string resultName;
void Search(string name)
{
if(ExistsInFirstStructure(name)) //name is in first data structure
Search(name + "1"); //add 1 and try again
else
if(ExistsInSecondStructure(name)) //name exists in second data structure
Search(name + "1"); //perform search again
else
resultName = name; //current name wasn't found in first and second data structures - we have result
}

Convert combobox string value to int

I have a question about converting types. I want to change the currently selected combobox value string to an int, but I get errors
My code:
int.Parse(age.SelectedItem.ToString());
What can I do for this problem?
Ok now we know the error, you can check for a null value before trying to parse it using:
if (comboBox1.SelectedItem != null)
{
int x = int.Parse(comboBox1.SelectedItem.ToString());
}
else { //Value is null }
You can avoid a null value being passed by setting the text property of the control to what ever default value you want.
If you are still not getting a value after making sure one is selected you really need to post your code.
TryParse is a good method for this sort of thing:
int value;
if (!Int32.TryParse(this.comboBoxNumeric.Text, out value))
{
//Do something fun...
}
Use a Convert.ToInt32 method. You can always use the databinding like this:
class A
{
public int ID{get;set;}
public string Name{get;set;}
}
cbo.DataSource = new A[]{new A{ID=1, Name="hello"}};
cbo.DisplayMember = "Name";
cbo.DisplayValue = "ID";
int id = Convert.ToInt32(cbo.SelectedValue);
A a = (A) cbo.SelectedItem;
int a_id = a.ID;
int a_name = a.Name;
If you use LINQ to DataSets, develop is very easy for C# program.
try
{
string name = comboBoxPort.SelectedItem.ToString();
int portBaudrate = Convert.ToInt32(comboBoxBaudrate.SelectedItem);
}
//just solved
//enjoy

Categories

Resources