how to compare asp.net radio button list values - asp.net

I am trying to fix a search tool for work. This is the first time I have encountered ASP.NET. The current search tool has a radio Button list with three options of how to search our local directory. However the person that worked on this project before me did not finish the code and has since quit. The radio buttons as they are not do not affect the search query as I have noticed that no matter what option you pick the query is the same.
This is my attempt to rewrite the search function to incorporate the three radio button options. However when I incorporate this function into the rest of the code the page does not render at all and I am not getting the error. I dont think I made an error in the query strings because I took the original one and made variations of it by omitting Contains statements. I'm assuming the error comes from my if statements or how I am trying to compare the asp.net RadioButtonList ListItem values.
protected void btnclick_WorkspaceSearch(object sender, EventArgs e){
string strSearchTerm=tbSearch.Text.Trim()
if (rblSearchOption.SelectedValue == "all"){
// Find the search term in either a file name or file content
string indexQuery = "SELECT docauthor,doctitle, FileName, Path, Write, Size, Rank";
indexQuery += "FROM " + "Workspace" + "..SCOPE() WHERE ";
indexQuery += "CONTAINS(FileName, '\"" + strSearchTerm + "\"') ";
indexQuery += "OR CONTAINS(Contents, '\"" + strSearchTerm + "\"') ";
indexQuery += "ORDER BY Rank DESC";
}
if (rblSearchOption.SelectedValue=="names"){
// Find the search term in a file name
string indexQuery = "SELECT docauthor,doctitle, FileName, Path, Write, Size, Rank";
indexQuery += "FROM " + "Workspace" + "..SCOPE() WHERE ";
indexQuery += "CONTAINS(FileName, '\"" + strSearchTerm + "\"') ";
indexQuery += "ORDER BY Rank DESC";
}
if (rblSearchOption.SelectedValue =="contents") {
// Find the search term in a file's content
string indexQuery = "SELECT docauthor,doctitle, FileName, Path, Write, Size, Rank";
indexQuery += "FROM " + "Workspace" + "..SCOPE() WHERE ";
indexQuery += "CONTAINS(FileName, '\"" + strSearchTerm + "\"') ";
indexQuery += "ORDER BY Rank DESC";
}
searchIndex(indexQuery);
lit_strQueryString.Text = indexQuery;
}

I figured out the problem. For those that commented thank you for your input I did make some necessary changes to help correct potential errors. As for the original question to compare listItem values the line that I used was :
if (rblSearchOption.SelectedItem.Value =="contents"){
//logic here
}
i had tried this before but it did not work. I'm assuming because of the errors pointed out in the comments.
Additional Notes(based on the comments):
The code above has a missing ; in line1
string index query should be declared and initiated outside of the if statements.
Once again thank you to those who attempted to help me.

Glad you found your problem, a bit unrelated but looking at your code I would say it needs some serious refactoring. This code can be simplified by:
1) Using a switch statement.This will help evaluating the selected value of the radio button list just once unlike your code
2) Using a StringBuilder to construct the query
3) Removing repetition - the append logic for names and contents is exactly the same you can remove the repetition by using two case expression and providing one statement to execute.
System.Text.StringBuilder indexQuery = new System.Text.StringBuilder();
indexQuery.Append("SELECT docauthor,doctitle, FileName, Path, Write, Size, Rank FROM Workspace..SCOPE() WHERE ");
switch(rblSearchOption.SelectedItem.Value)
{
case "all":
indexQuery.AppendFormat("CONTAINS(FileName,'{0}') ",strSearchTerm);
indexQuery.AppendFormat("OR CONTAINS(Contents,'{0}')",strSearchTerm);
indexQuery.AppendLine("ORDER BY Rank DESC");
break;
case "names":
case "contents":
indexQuery.AppendFormat("CONTAINS(FileName,'{0}')",strSearchTerm);
indexQuery.Append("ORDER BY Rank DESC");
break;
}
searchIndex(indexQuery.ToString());
lit_strQueryString.Text = indexQuery;

Related

SQLIte not displaying all of the results correctly in ListView

I am having trouble with displaying the results in the search activity of my app. I wonder where it went wrong.
The aim of the function below is to search the input query of the user and find it in every files listed. But the results only matches one data eventhough the query is also present in the other files. Here is the code.
public void searchFiles(File[] filelist, String query, String querysearch, String[] namesOfFiles){
querysearch = "SELECT * FROM Data WHERE ObjectID = ? ";
int temp2 = filelist.length;
for (int i = (temp2-1); i >= 0; i--) {
if(!(filelist[i].getName().equals("DataObjectDB.db")) && !(filelist[i].getName().endsWith("-journal"))){
temp1 = filelist[i].getName();
namesOfFiles[i] = temp1.replaceAll(".db$", "");
Toast.makeText(getApplicationContext(),"Searching " + query + " in: " + namesOfFiles[i], Toast.LENGTH_SHORT).show();
DatabaseHelper db1 = new DatabaseHelper(getApplicationContext(),namesOfFiles[i]);
SQLiteDatabase sqldb = db1.getWritableDatabase();
cursor = sqldb.rawQuery(querysearch, new String[]{query});
Toast.makeText(getApplicationContext(),cursor.toString(), Toast.LENGTH_SHORT).show();
}
}
final ListView listView = (ListView) findViewById(R.id.results_listview);
SearchAdapter adapter = new SearchAdapter(this, R.layout.results_column, cursor,0 );
listView.setAdapter(adapter);
}
The searchFiles() function passes the filelist, query, querysearch and namesOfFiles where 1) filelist contains the list of files in the source folder 2) query is the user input he/she wants to search 3) querysearch is the select statement 3) namesofFiles is just an empty string.
I indicate a toast to see if the code traverses through all the folders. And yes it is. But I don't know why it is not displaying all the results.
Any help? Thanks!
Found an answer on different posts. Basically, you just have to use hashmap and arraylist first before setting up the adapter directly.

My datareader has row(s), but I am failing to get the record(s) to textbox from datareader

can anybody tell me where I am doing wrong.I am trying to develop a small site on my own using c#.I am unable to show the record which was fetched from datareader.
{
SqlConnection cone = new SqlConnection("User id=...;Password=;...");
SqlCommand conecmd = new SqlCommand("select bankbalance from bank where bankpassword='" + txtboxbankpassword.Text + "'", cone);
cone.Open();
SqlDataReader drcone = conecmd.ExecuteReader();
if (drcone.HasRows) // says it has row(s) i.e., Hasrows=true
{
while (drcone.Read()) // here its value is false
{
lblremainingbankbalance.Text = drcone["bankbalance"].ToString();
}
int a;
a = Convert.ToInt32(lblremainingbankbalance.Text);
lblmsg.Text = "Transaction successful.Please wait while we redirect you to mypage and your current " + bankstore + " accountbalance is " + a + "";
Response.AddHeader("REFRESH", "5;URL=Mypage.aspx");
txtboxbankpassword.Text = "";
} else {
lblmsg.Text = "Norecord(s)";
}
}
Try to run your query in SQL server and see if it shows some rows because i don't see any errors in code also trim the text of your textbox like this
txtboxbankpassword.Text.Trim()
Also close you connection when you are done with reading rows from datareader.
your case is very strange.. if drcone.HasRowsis true drcone.Read() have to return true... minimum for one time..
Are you debugging the code and add drcone.Read() to quickwatch or have it in your watchlist? Because, then it will run the method Read() before your while loop. Next time when you call Read() (in your while-loop) it will return false..
You get one row, the reader aligns the reader to the first row (in whatchlist), and returns false in your while loop and saying "there are no rows left after this one".
See this link Here for the documentation on this: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.read.aspx
if you have only a singlerow, the reader "is on position -1".. after drcone.Read() (return true) set the position to 0 (1 and last row).. next time you call drcone.Read() it will return false.. because there are no rows left after this one (reader is on position 0)

Depending source for drop down list

I have one drop down list in my pages that its source comes of below code. Now I like to put 1 text box adjusted on my drop down list and when I type on that, source of drop down list (DocumentNo) depend on what I type in the text box and when text box is null drop downs list shows all the (DocumentNo) , please help how I have to change my code,
protected void ddlProjectDocument_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var query = from p in _DataContext.tblDocuments
orderby p.DocumentNo
select p;
int maxs = 0;
foreach (tblDocument v in query)
{
if (v.DocumentNo.Length > maxs)
maxs = v.DocumentNo.Length;
}
foreach (tblDocument vv in query)
{
string doctitle = vv.DocumentNo;
for (int i = vv.DocumentNo.Length; i < maxs; i++)
{
doctitle += " ";
}
doctitle += " | ";
doctitle += vv.TITLE;
// Use HtmlDecode to correctly show the spaces
doctitle = HttpUtility.HtmlDecode(doctitle);
ddlProjectDocument.Items.Add(new ListItem(doctitle, vv.DocId.ToString()));
}
}
First, I would highly recommend storing the result of that query at the beginning of the method into something like a session variable so that you don't have to continually query the database every time you hit this page.
Second, you should use the OnTextChanged event in ASP.NET to solve this problem. Put in the OnTextChanged attribute to point to a method in your code behind that will grab the query result values (now found in your session variable) and will reset what is contained in ddlProjectDocument.Items to anything that matched what was being written by using String.StartsWith():
var newListOfThings = queryResults.Where(q => q.DocumentNo.StartsWith(MyTextBox.Value));
At this point all you need to do is do that same loop that you did at the end of the method above to introduce the correct formatting.

SQL always returning same results

I'm trying to do a search on a table in my database where it returns the top 50 rows with a firstname like the search term being passed to the function, but its always returning the same 50 results
My sql looks like this:
Select TOP(50) *
FROM [database].[dbo].[records]
WHERE (A_1STNAME LIKE '" + #searchTerm + "%')
ORDER BY A_RECID
When I run this query in Visual Studios query window, it works as expected but when I run it through my ASP.NET application, it always returns the same 50 results, and only one of them has a first name close to the searchTerm I passed to it.
here is the page code that runs the function:
protected void Page_Load(object sender, EventArgs e)
{
_migrated_data data = new _migrated_data();
DataSet ds = data.Search(Request.QueryString.Get("query"), "A_RECID", 50);
if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
{
rpt_Data.DataSource = ds.Tables[0].DefaultView;
rpt_Data.DataBind();
}
}
and here is the search method of _migrated_data:
public DataSet Search(String #pSearchTerm, String #pSortBy, int #pRowCount)
{
DataSet ds = new DataSet();
OleDbConnection objOleDBConn;
OleDbDataAdapter objOleDBDa;
objOleDBConn = new OleDbConnection(ClearingHouse_OLEDDB);
objOleDBConn.Open();
string lSQL = "SELECT TOP(50) * FROM [database].[dbo].[records]";
lSQL += " WHERE (A_1STNAME LIKE #searchTerm ) ORDER BY #sortBy";
SqlCommand t = new SqlCommand(lSQL);
if (pSearchTerm != null && pSearchTerm != "")
{
t.Parameters.AddWithValue("#searchTerm", #pSearchTerm + "%");
}
if (pSortBy != null && pSortBy != "")
{
t.Parameters.AddWithValue("#sortBy", #pSortBy);
}
else
{
t.Parameters.AddWithValue("#sortBy", "A_RECID");
}
objOleDBDa = new OleDbDataAdapter(t.CommandText, objOleDBConn);
objOleDBDa.SelectCommand.CommandType = CommandType.Text;
objOleDBDa.Fill(ds);
objOleDBConn.Close();
return ds;
}
Using locals to view the final CommandText of t, I get the sql results I gave above.
Any help is greatly appriciated :)
AS Rob Rodi said, first of all, to get the results begining with a value you will need % char at the end of the therm:
Select TOP(50) *
FROM [database].[dbo].[records]
WHERE (A_1STNAME LIKE '" + #searchTerm + "%')
ORDER BY A_RECID
Second, probably your searchTerm is empty, so it's grabbing always the same results.
Debug your app and watch the variable to see if it's receiving some value.
You are having SQL injection there. Also it looks like the %-signs are missing.
The fact, that the query works in a query window and not in your app means, that the error is not in your query! Did you think about that? Probably, you should post code of your ASP.NET app.
It sounds like your parameter isn't being correctly passed to your data layer. Easiest way to find out if that's the case is to turn on Sql Profiler and check to see if it's being passed. If it is, your sql's to blame. If it's not, it's your application. You can then use the debugger on your application to work your way up the stack to see where the problem lies.

get value from Linq and put it in the tex box

i have this code
MasterSoapClient sp = new MasterSoapClient();
MasterData[] lstMasterData = sp.GetActivityType(stid, null, 1);
grdEditActivityType.DataSource = lstMasterData;
grdEditActivityType.DataBind();
Session["opType"] = 2;
txtActivityCode.Text = lstMasterData.ToString();
txtActivityCode.DataBind();
here i called web service and put all data in this Gridview "grdEditActivityType "
and already workin
but there is column of lstMasterData i want to put it in the text box out of the grid
how i can do this ?
txtActivityCode.Text is a Property that you can use to assign a text value to the TextBox.
If you use txtActivity.Text = " some input "; Your textbox will contain the text " some input ".
You don't need to Bind txtActivityCode afterwards.
Having this clarified the next step is to create the string you want using to assign to the text box.
string s = "";
foreach( var masterData in lstMasterData )
{
s += masterData.SomeProperty; // s += masterData.ToString(); maybe, it depends on what do you want to put in the textbox;
}
txtActivityCode.Text = s;
And that's all.
I would suggest to start look more over ASP.NET tutorials to understand better how this framework works.

Resources