Where condition in LinqDataSource for string in ASP.NET - asp.net

I am trying to populate data in gridview by using LinqDataSource and in the where condition of LinqDataSource1 - programmatically I am not sure about the syntax on how to pass a string value to a particular column?
What is the syntax for where condition in LinqDataSource on a string programmatically?
I am familiar with the one in int:
int id = 5;
for example:
LinqDataSource1.Where = "ID =" +id;
But, not sure about the syntax for string.
Please suggest something!

Ok, finally I got the syntax for string in LinqDataSource:
LinqDataSource1.Where = "Title.Contains("+ "\"" + txtTitle.Text + "\""+ ")";

Related

How to make value of a column name appear with single apostrophe in sql statement of sql helper inside asp. net

SQLHelper sqhlpr = new SQLHelper();
sqhlpr.SqlText = "Select StudentName from tblStudentInfo where class=" + NurseryButton.Text;
DataTable dt = sqhlpr.getDataTable(false);
This is my code.Now the result of sqhlpr.sqlText is
select StudentName from tblStudentInfo where class= **Nursery**
(i.e.NurseryButton.Text=Nursery) but the result that i want is select StudentName from tblStudentInfo where class= 'Nursery'.How can this be done??? This looks simple but I can't just figure it out...
"Select StudentName from tblStudentInfo where class='" + NurseryButton.Text + "'";
But you definitively should not use it that way! (SQL Injection)
Here is a good answer: Sql inline query with parameters. Parameter is not read when the query is executed
Your query is a string. You do:
result = "somestring" + someVariable;
Now you want to enclose someVariable in sinlge quotes, which is done like this:
result = "somestring" + "'" + someVariable + "'";
Or shorter:
result = "somestring'" + someVariable + "'";
However is is worth noting that manually building queries is quite "not done". You should look at tools like parameterized queries or even O/R mappers like Entity Framework.
The following code will do what you want:
SQLHelper sqhlpr = new SQLHelper();
sqhlpr.SqlText = "Select StudentName from tblStudentInfo where class = '" + NurseryButton.Text + "'";
DataTable dt = sqhlpr.getDataTable(false);
You need to think about two more things though:
What happens if someone puts an apostrophe in the NurseryButton.Text somehow
Will SQLHelper protect you from this sort of thing, or do you need to do it yourself
You should consider parametrized querying or stored procedures in some way to make sure that your input to the database is done safely.

How to use text box as date in ADO.NET

I have an ASP.NET wizard where a user fills in their personal details and the values of the text boxes are inserted into a MS SQL record.
However, when inserting the record, I get the following error:
SQL Server error #241: Conversion failed when converting date and/or
time from character string
Code:
string insertSQL;
insertSQL = "INSERT INTO member (";
insertSQL += "UserId, mem_dob,) ";
insertSQL += "VALUES (";
insertSQL += "#UserId, #mem_dob";
insertSQL += ")";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(insertSQL, con);
//Add the parameters.
cmd.Parameters.AddWithValue("#UserId", providerIdKeyString);
cmd.Parameters.AddWithValue("#mem_dob", DateOfBirth.Text);
Any ideas the best way to fix? Should I not be using a text box but something else?
I wanted to keep the web form simple - it validates the dates OK so thought the date should be valid.
Thanks
You should simply parse the Text to a valid DateTime.
cmd.Parameters.AddWithValue("#mem_dob", DateTime.Parse(DateOfBirth.Text));
http://msdn.microsoft.com/en-us/library/1k1skd40%28v=VS.100%29.aspx
Of course you should have already validated that the entered "date" is valid at this stage.
Sounds like the date entered in your Text Box is an invalid date according to SQL. Before attempting to add the date as a parameter, first check it's validity. e.g.
DateTime myDate;
if(textBox1.TryParse(DateOfBirth.Text, out myDate))
{
// Date is valid.
} else
{
// Take corrective actions to fix the date.
}
Simply attempting to parse the date without knowing whether it's valid or not will leave your application open to a failure, as you simply shouldn't trust the user to enter a valid date.
DateTime t;
String Date = String.Empty;
if (DateTime.TryParse(Date, out t))
{
cmd.Parameters.AddWithValue("#mem_dob", t);
}
You should have to create simple user-control that contains three dropdown controls - for day, month and year and a public property/method to set/get date. You may think about ASP.NET Ajax controls.
In case if you want to use Textbox then restrict the user input via CompareValidator control or some sort of JavaScript and regular expression.
To parse date string use DateTime.TryParse, or DateTime.ParseExact (DateTime.TryParseExact) method.
string[] inputFormat = {"dd-MM-yy","dd/mm/yy","dd-MMM-yyyy"};
string userDate = "31-12-11";
DateTime date;
if (DateTime.TryParseExact(userDate,
inputFormat,
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out date))
{
//valid
}

Conversion from string "ACECATN000001" to type 'Integer' is not valid

I am a new in using asp.net i have recieving an error of "Conversion from string "ACECATN000001" to type 'Integer' is not valid." can anyone help me how to solve this?? thanks in advance :D
If lbl_productcatcode.Text = "ACECATN000001" Then
txt_productcode.Text = Format(CInt(rdr.Item(0).ToString) + 1, "1000000")
End If
End If
cmd1.Connection.Close()
End Sub
You've posted some code but not said which line has the error, I presume it is this one:
cmd1.CommandText = "Select CategoryID from CategoryTable where ProductCategory = '" & DropDownList1.Text & "'"
If the CategoryId column on the CategoryTable is of type integer, then you cannot compare it against a string value. I would guess that you need to use the ID of the item bound to the DropdownList, IIRC there should be a SelectedValue property on the dropdown that you can use for this.
cmd1.CommandText = "Select CategoryID from CategoryTable where ProductCategory = " & DropDownList1.SelectedValue
Note the absense of single quotes as you will be injecting an int value into the sql statement.
Firstly: CInt(s) converts s(s being a string) to integer and is only valid if s contains only numbers(no letters).
In this line:
txt_productcode.Text = Format(CInt(rdr.Item(0).ToString) + 1, "1000000")
you are trying to convert rdr.Item(0).ToString to an integer. According to your code,
rdr.Item(0).ToString returns "ACECATN000001" which contains letters and hence cannot be converted to integer.
What exactly are u wanting to do in that line?

Insert the date into table

I am trying to get From date and To date in two text boxes using the calender control and then trying to insert this value in a table. How can I proceed with this??
Please help..
string comstr = "insert into ATM_DETAILS_TB values(" + txtpin.Text + ",'" + Convert.ToDateTime(txtvldfrm.Text) + "','" + Convert.ToDateTime(txtvldto.Text) + "'," + Convert.ToInt32(ddlaccno.SelectedValue) + ",'" + Session["strUid"].ToString() + "')";
while using this code it shows error like "String was not recognized as a valid DateTime"
what should I do??
Use Validation controls to validate that the values in textbox values are valid dates.
Your code us contencating strings directly from user input. This opens you up to all sorts of nasty attacks, the primary being SQL Injection. Use parameterized queries instead.
Always use DateTime.TryParse or TryParseExact method to parse the date.
DateTime vldDate;
bool isValid=false;
if(DateTime.TryParse(txtvldfrm.Text,out vldDate))
{
isValid=true;
}
....
if(isValid)
{
command.Parametter.Add("#vldto",SqlDbType.DateTime).Value=vldDate;
command.Parametter.Add("#strUid",SqlDbType.VarChar,30).Value=Session["strUid"];
.....
}
You Use from parameterized queries like this:
string comstr = "insert into ATM_DETAILS_TB values(#pin,#vldfrm,#vldto,#ddlaccno,#strUid)";
YourCommand.Parametter.AddWithValue("#vldto",Convert.ToDateTime(txtvldto.Text));
YourCommand.Parametter.AddWithValue("#strUid",Session["strUid"].ToString());
....Define the Other Paraametter
Edit----
check this question String was not rec...

FindControl in Asp.Net

I'm trying to find a control in a page. The Id is available as a server control (CheckBox)
This throws exception "not able to convert string to double"
Dim taskId As HtmlInputCheckBox
i =10
taskId = Me.FindControl("chkTaskOption_" + i)
taskId.Checked = True
Can any one tell me where i'm wrong.
Your problem is that you need to use & instead of + to concatenate two strings in VB.NET. Change this line:
taskId = Me.FindControl("chkTaskOption_" & i)
For further reading, there's a good discussion about this in the answers to this question.
You might just be missing a cast of the type returned from FindControl. Or on the variable i. I can't remember if VB.net will convert for you.
i =10
Dim taskId As HtmlInputCheckBox
taskId = CType(Me.FindControl("chkTaskOption_" & i.ToString()), HtmlInputCheckBox)
taskId.Checked = True

Resources