Any simple way of implementing highligh text results in gridview? - c#

I used the search function and I've seen a lot of topics about "how to highlight a text " but I couldn't find a way to implement it in my asp.net website project.
I'm using a gridview and for search function I'm using this :
SqlDataSource1.SelectCommand = "select * from TableName where Name like '%" + TextBox1.Text + "%' or SecName like '%" + TextBox1.Text + "%'";
SqlDataSource1.DataBind();
How can I do it ? I would like someone to explain step by step , I need to do this for tomorrow and I'm not very advanced. ty

I think it could help you try it and add
$(document).ready(function () {
$('#txt_Search').keyup(function () {
searchTable($(this).val());
});
function searchTable(inputVal) {
var table = $('#GridView1');
table.find('tr').each(function (index, row) {
var allCells = $(row).find('td');
if (allCells.length > 0) {
var found = false;
allCells.each(
function (index, td) {
var regExp = new RegExp(inputVal, 'i');
if (regExp.test($(td).text())) {
found = true;
return false;
}});
if (found == true) $(row).addCss();
}
});
}
});

Related

c# equivalent to document.getElementById("ListBox"+i+"Item"+j).selected=true

I've created a dynamic webpage using strictly html, javascript, and MS Access. While it was functional, locally, there were complications deploying it. Since I have ported the data to MySQL and am trying to use Visual Studio's aspx.cs to do much of what the javascript did previously.
I have a screen that populates a dynamic set of rows based on a query result (two rows per record for aesthetics), one of the cells contains a drop down menu(html select/ asp:ListBox).
When I had everything only on javascript, I could create the cell, then create its contents, then set the selected value using:
document.getElementById("StatusDD" + rowCount).value = reader.GetValue(i);
From what I've gathered so far, the rough equivalent is:
ListItem li = StatusDD1.Items.FindByValue(reader.GetValue(i));
li.Selected = true;
However, I cannot simply hardcode StatusDD1 thru StatusDDx (for one, at the beginning my hardcoded set might be larger than the number of records returned, and two eventually the rows returned will be larger than the set of hardcoded values).
So what I did was I created the following function:
protected void setSelected(string selectId, string value)
{
/*Need to put something here to make the following work*/
selectId.Items.FindByValue(value).Selected = true;
}
The selectId being passed in is the name/id of the ListBox and the value is the value coming back from the query.
It's called like:
setSelected("StatusDD" + rowCount, (string)reader.GetValue(i));
If I could, for lack of better phrase, materialize the name created by "StatusDD"+rowCount, I could pass that name in as if I was passing in a ListBox, rather than a string.
Alternatively, if there was a way to select the ListBox from an array where I could do a conditional check WHERE/IF ListBox.Name = selectId, something like the following PseudoCode:
ListBox a = ListBox.NameMatches(selectId);
a.Items.FindByValue(value).Selected = true;
Currently ListBoxes are being created by defining the box in a string and then passing that string into an HtmlTableCell:
HtmlTable myTable = new HtmlTable();
HtmlTableRow newRow;
string cellId;
string cellContents;
int rowCount = 1;
string statusDisabled = "";
while (reader.Read()){
newRow = new HtmlTableRow();
myTable.Rows.Add( newRow );
...
...
cellContents = "<asp:ListBox name='StatusDD" + rowCount + "' id='StatusDD" + rowCount + "' style='width:100%; " + statusDisabled + "' value='" + reader.GetValue(i) + "' onchange='markNeedSave(" + (rowCount + 1) + ")'><asp:ListItem value='0'></asp:ListItem><asp:ListItem value='1'>New</asp:ListItem>....asp:ListBox>";
newRow.Cells.Add(new HtmlTableCell{InnerHtml = cellContents});
}
If it helps, here's how I had it working in javascript:
while (!rs.EOF) {
rowa = table.insertRow(rowCount);
rowa.id = "RECORD" + rowCount + "a";
cell = rowa.insertCell(i + 1);
cell.id = "RECORD" + rowCount + "_CELL" + (i + 1);
for (i = 0; i < 8; i++) {
cell.innerHTML = "<select name='StatusDD" + rowCount + "' id='StatusDD" + rowCount + "' style='width:100%' value='" + rs.fields(i).value + "' onchange='markNeedSave(" + (rowCount + 1) + ")'><option value='NONE'></option><option value='New'>New</option>...</select>";
if (readonly) {
document.getElementById("StatusDD" + rowCount).disabled = true;
}
document.getElementById("StatusDD" + rowCount).value = rs.fields(i).value;
}
...
}
OK, got the ListBox to work, but as I was researching, and when I finally got it to work, I discovered that what I wanted was the DropDownList, not the ListBox, but the same fixes needed to be done in order to get either to work.
I use the following function now:
protected void setSelected(string selectId, string value)
{
PlaceHolder TCS = Page.FindControl("TestingCS") as PlaceHolder;
DropDownList ddl = TCS.FindControl(selectId) as DropDownList;
if (ddl != null)
{
ddl.SelectedValue = value;
ListItem item = ddl.Items.FindByValue(value);
if(item != null)
{ item.Selected = true;}
}
}
Also, for my cell contents that just contain data using the following is fine:
cellContents = "<someString>";
newRow.Cells.Add(new HtmlTableCell{InnerHtml = cellContents});
but for my drop down (or list box) I need to use:
cell = new HtmlTableCell();
newRow.Cells.Add(cell);
DropList = new DropDownList();
DropList.ID = "StatusDD" + rowCount;
DropList.Items.Add(new ListItem("", "0"));
DropList.Items.Add(new ListItem("New", "1"));
...
cell.Controls.Add(DropList);
setSelected(DropList.ID, (string)(reader.GetValue(i)));
A smoother solution:
protected void setSelected(DropDownList ddl, string value)
{
ListItem item = ddl.Items.FindByValue(value);
if (item != null)
{ item.Selected = true; }
}
...
protected void accessRecord()
{
...
DropList = new DropDownList();
DropList.ID = "StatusDD" + rowCount;
DropList.Attributes["onChange"] = "javascript:markNeedSave(" + rowCount + ");";
DropList.Items.Add(new ListItem("", "0"));
DropList.Items.Add(new ListItem("New", "1"));
...
cell.Controls.Add(DropList);
setSelected(DropList,(string)reader.GetValue(i));
}
...
It sounds like the function you're looking for is FindControl. This can be used from the Page, or any parent control you might have created to hold your output.
An example implementation of your setSelected method might look like this:
protected void SetSelected(string selectId, string value)
{
var lb = Page.FindControl(selectId) as ListBox;
if (lb != null)
{
var item = lb.Items.FindByValue(value)
if(item != null)
item.Selected = true;
}
}

jQuery Autocomplete from database when users starts to type

I'm trying to get a autocomplete function to work.
It works when I get my database values on Page_Load event but it takes forever loading the page because it's a large set of data that needs to be available to my autocomplete textfield.
Better would be to do the db query when users start typing.
I've tried different approaches but none works.
This is my code so far;
<script type="text/javascript">
$(document).ready(function () {
SearchText();
function SearchText() {
$("#<%= artnr1.ClientID %>").autocomplete({
source: function (request, response) {
$.ajax({
url: "GetArticles.asmx/searcharticles",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: "{ 'term' : '" + $("#<%= artnr1.ClientID %>").val() + "'}",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.label,
value: item.value,
desc: item.desc
}
}))
//debugger;
},
error: function (result) {
alert("Error");
}
});
},
minLength: 1,
delay: 1000,
autoFocus: true,
change: function (event, ui) {
$("#<%= artben1.ClientID %>").val(ui.item.desc);//or ui.item.desc perhaps
}
}).focus(function () {
$(this).data("uiAutocomplete").search($(this).val());
});
}
});
</script>
<asp:TextBox runat="server" id="artnr1" placeholder="Artnr" value=""/>
This is my asmx file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data.Odbc;
using System.Web.Configuration;
using System.Data;
using Pervasive.Data.SqlClient;
using Pervasive.Data.Common;
using Newtonsoft.Json;
namespace cDealer
{
/// <summary>
/// Summary description for GetPyART
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class GetPyART : System.Web.Services.WebService
{
[WebMethod]
public List<string> searcharticles(string term)
{
string strLagerSaldo = string.Empty;
string strLagerReserv = string.Empty;
string strLagerBest = string.Empty;
string strLagerPris = string.Empty;
string strArtKod = string.Empty;
string strEANKod = string.Empty;
string strBen = string.Empty;
string strartnrvalue = string.Empty;
string pyarticles = string.Empty;
OdbcConnection dbPyConn = new OdbcConnection(WebConfigurationManager.ConnectionStrings["ConnPyString"].ConnectionString);
string pysql = #"select D1001_Artikelkod, D1021_Benämning, D1132_Saldo, D1134_Reserverat, D1136_Beställt, D1154_Grundpris, " + (char)34 + "D1109_EAN-kod" + (char)34 + " from PULAGER WHERE D1055_Kalkyltyp <> '60' AND (D1001_Artikelkod Like '%" + term + "%' OR D1021_Benämning Like '%" + term + "%') ORDER By D1001_Artikelkod DESC";
using (OdbcConnection connection = new OdbcConnection(WebConfigurationManager.ConnectionStrings["ConnPyString"].ConnectionString))
{
OdbcCommand command = new OdbcCommand(pysql, connection);
List<string> articles = new List<string>();
connection.Open();
OdbcDataReader reader = command.ExecuteReader();
// Call Read before accessing data.
while (reader.Read())
{
if (reader.HasRows)
{
if (reader["D1132_Saldo"] != DBNull.Value)
{
strLagerSaldo = reader.GetDecimal(reader.GetOrdinal("D1132_Saldo")).ToString("G29").TrimEnd();
}
else
{
strLagerSaldo = "0";
}
if (reader["D1134_Reserverat"] != DBNull.Value)
{
strLagerReserv = reader.GetDecimal(reader.GetOrdinal("D1134_Reserverat")).ToString("G29").TrimEnd();
}
else
{
strLagerReserv = "0";
}
if (reader["D1136_Beställt"] != DBNull.Value)
{
strLagerBest = reader.GetDecimal(reader.GetOrdinal("D1136_Beställt")).ToString("G29").TrimEnd();
}
else
{
strLagerBest = "0";
}
if (reader["D1154_Grundpris"] != DBNull.Value)
{
strLagerPris = reader.GetDecimal(reader.GetOrdinal("D1154_Grundpris")).ToString("G29").TrimEnd();
strLagerPris = String.Format("{0:C}", Convert.ToDouble(strLagerPris));
}
else
{
strLagerPris = "0";
}
if (reader["D1001_Artikelkod"] != DBNull.Value)
{
strArtKod = reader.GetString(reader.GetOrdinal("D1001_Artikelkod")).TrimEnd();
}
else
{
strArtKod = "";
}
if (reader["D1021_Benämning"] != DBNull.Value)
{
strBen = reader.GetString(reader.GetOrdinal("D1021_Benämning")).TrimEnd().Replace("" + (char)34 + "", "´´");
}
else
{
strBen = "";
}
if (reader["D1109_EAN-kod"] != DBNull.Value)
{
strEANKod = reader.GetString(reader.GetOrdinal("D1109_EAN-kod")).TrimEnd();
}
else
{
strEANKod = "";
}
articles.Add("{label:" + strArtKod + " - " + strEANKod + " - " + strBen + " - L.Saldo: " + strLagerSaldo + " - Reserv.: " + strLagerReserv + " - Beställt: " + strLagerBest + " - KPris: " + strLagerPris + ", value: " + strArtKod + ", desc:" + strBen + "}");
//Response.Write(strartsearch);
}
else
{
//Response.Redirect("https://www.google.se");
}
}
// Call Close when done reading.
reader.Close();
return articles;
}
}
}
}
When I start typing and then pauses the event is fired. I can in firebug see that I get a json response like this;
"[{"label":"771678 - Fuel injector/10/kw","value":"771678","desc":"Fuel injector for Ford"}]"
But no autocomplete shows up.
I can in the debugger see this errors
TypeError: invalid 'in' operand a
TypeError: ui.item is null
I have no idéa where that is and whats wrong. Can anyone please assist or point me to a really easy guide with all bits explained for C# webforms.
Thanks.
The problem is probally that the JSON is incorrect. After what you have posted in the comments I would say, the quote before the Array is the issue.
My response looks like this: {"d":"[{\"label\"
Here you can find some examples and some more information to JSON https://en.wikipedia.org/wiki/JSON
Just to sum up:
if pure json is being send escaping is not necesary, in a string you have to escape (or combine with single quotes)
{
"name": "test",
"array": [ 1, 2, 3, 4], /* here are no quotes around the square brakets */
"object": {"prop1":1, "prop2":2}
}
A good way to test is create a textfile, change the file extension to ".json", and add the JSON. Like this you can experiment with the quotes and so. to be sure that everything come back correct from the server, you can also change the return type to text and print the message into the console.
If the problem still persits post the raw json, which was sent from the Server.
Update:
here https://embed.plnkr.co/OSYJQZ/ is a working example on firefox 45+ with your corrected json.
you can see how the json should look like (and copy out in needed).
Update2
The Problem is probably because the nested object in the Json is created as a string (List<string>). I would suggest to write something like this (or use the ResponseFormat Attribute, depence of the usecase )
//helper Object for the data Structure
class Helper{
public string label;
public string value;
public string desc;
}
then in the code
//create the list of Objects
List<Helper> list = new List<Helper>();
list.Add (new Helper(){
label="771678 - - Fuel injector for Ford - L.Saldo: 0 - Reserv.: 0 - Order: 0 - KPris : 0,00 kr",
value="771678",
desc="Fuel injector for Ford" }
);
//serialize the Object into Vaild JSON
var jsonString = (new System.Web.Script.Serialization.JavaScriptSerializer()).Serialize(list);
Here are some other Questions on SO the deal with similar problems
https://stackoverflow.com/a/3196640/1679286
https://stackoverflow.com/a/19564022/1679286
Update 3:
Here is a solution I wipped up, its only a ashx Handler, but it is the fasted I could do without opening VS. I Hope this helps
<%# WebHandler Language="C#" Class="JsonHandler" %>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
public class JsonHandler : IHttpHandler
{
class Helper{
public string label;
public string value;
public string desc;
}
public void ProcessRequest(HttpContext context)
{
List<Helper> list = new List<Helper>();
list.Add (new Helper(){
label="771678 - - Fuel injector for Ford - L.Saldo: 0 - Reserv.: 0 - Order: 0 - KPris : 0,00 kr",
value="771678",
desc="Fuel injector for Ford" }
);
context.Response.ContentType = "application/json";
var jsonString = (new System.Web.Script.Serialization.JavaScriptSerializer()).Serialize(list);
context.Response.Write(jsonString);
}
public bool IsReusable
{
get
{
return false;
}
}
}

javascript function not being called

I have a dropdownlist and a fileupload control in a panel which is added with other controls in an UpdatePanel. When a value is selected from the dropdown and a file is uploaded, the Upload button is enabled. For this I have a javascript function as follows:
function SetUploadButtonEnabled(controlPanel, fileUploadId) {
var docTypesList = controlPanel.find("select");
var gotListVal = docTypesList.val() != "";
var fileUpload = $find(fileUploadId);
var gotFileVal = fileUpload.getUploadedFiles().length > 0;
var enable = gotListVal && gotFileVal;
if (enable) {
controlPanel.find(".GxButtonBlue").removeAttr("disabled");
}
else {
controlPanel.find(".GxButtonBlue").attr("disabled", true);
}
}
I am trying to call it from code behind as follows, but the function is not being called:
string script = "<script type=\"text/javascript\">"
+ "\n $(document).ready(function (){"
+ "\n $(document).on(\"change\", \"#" + this._DdDocumentTypes.ClientID + "\", function(event){"
+ "\n var docUploadControlPanel = $(this).closest(\"#" + this._DocUploadControlPanel.ClientID + "\");"
+ "\n SetUploadButtonEnabled(docUploadControlPanel, \"" + this._fiInput.ClientID + "\");"
+ "\n });"
+ "\n });"
+ "\n "
+ "</script>";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "DocumentAjaxUploadCtrlScript_" + this.ClientID, script);
Since an Update Panel is there I even tried:
ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "DocumentAjaxUploadCtrlScript_" + this.ClientID, script, true);
Please help me find why the function is never called!
Here's one way to do it. The key here is the pageComponents object.
ASPX or User Control
<script>
var pageComponents = {
documentTypeSelector: "#<%= _DdDocumentTypes.ClientID %>",
uploadControlSelector: "#<%= _DocUploadControlPanel.ClientID %>",
fiInputSelector: "#<%= _fiInput.ClientID %>"
};
</script>
JavaScript Place after the above
function SetUploadButtonEnabled(controlPanel, fileUploadId) {
var docTypesList = controlPanel.find("select");
var gotListVal = docTypesList.val() != "";
var fileUpload = $find(fileUploadId);
var gotFileVal = fileUpload.getUploadedFiles().length > 0;
var enable = gotListVal && gotFileVal;
if (enable) {
controlPanel.find(".GxButtonBlue").removeAttr("disabled");
}
else {
controlPanel.find(".GxButtonBlue").attr("disabled", true);
}
}
$(document).ready(function (){
$(document).on("change", pageComponents.documentTypeSelector, function(event){
var docUploadControlPanel = $(this).closest(pageComponents.uploadControlSelector);
SetUploadButtonEnabled(docUploadControlPanel, pageComponents.fiInputSelector);
});
});
Remarks
You can avoid using the "bee sting" syntax above by setting the control ClientIDMode property to Static (assuming you're using only ASP.NET Page, not a user control. Then your JavaScript would look like below:
$(document).ready(function (){
$(document).on("change", "#documentType", function(event){
var docUploadControlPanel = $(this).closest("#uploadControl");
SetUploadButtonEnabled(docUploadControlPanel, "#fiInput");
});
});
In addition the line:
var docUploadControlPanel = $(this).closest(pageComponents.uploadControlSelector);
could be written as:
var docUploadControlPanel = $(pageComponents.uploadControlSelector);
since ClientID always returns a unique element ID for the entire page.

Creating jquery object array and posting its values on form submit

I have dynamicly added html elements(selectlists) in a form :
//Dynamicly adding selectlist elements
function newshit() {
i = i + 1
$("#mytable").append("<tr><td><div id='div" + i + "'><select id='elem" + i + "' name='elem" + i + "' class='ted'></select><input type='button' value='-' id='buttonminus" + i + "' style='width:5%;' onclick='removeelem(elem" + i + ",buttonminus" + i + "," + i + ")'/></div></td></tr>")
getitems("elem" + i)
}
//filling lists
function getitems(item) {
$.getJSON('#Url.Content("~/Stok/Items/")', {}, function (data) {
$.each(data, function (i, c) {
$("#" + item).append("<option value='" + c.Value + "' title='" + c.Text + "' label='" + c.Text + "'>" + c.Text + "</option>")
})
})
}
//removing element, when button next to it used
function removeelem(elem,buttonminus,i) {
if ($("select").length > 1) {
$("#div" + i).closest('tr').empty().remove()
} else if ($("select").length <= 1) {
alert("At least 1 of items must be chosen to create a group!")
}
}
//checking elements and values existence
function check() {
var slcts = $("select").serialize();
alert(slcts)
}
im trying to get the value of each selectlist's selected option value and put them into an array than send them to my controller on form submit.
How can i achive this?
Need to check this, but I think that the following should work:
Change your code so that the format of your ids is something like:
id="elem[0]"
Then if your controller has a signature something like this:
public ActionResult Something(IEnumerable<string> elem)
{
}
Then his should "just work".
You could use something like -
var selectdata = $("select").serialize()
This will return a string in the form <select name attribute1>=<chosen value1>&<select name attribute2>=<chosen value2> etc. You'd need to add a 'name' attribute to your select HTML when you create it for this to work.
Demo - http://jsfiddle.net/ipr101/fZXha/
You could then put the selectdata variable in a hidden field before the form was posted or send it via AJAX using the ajax or post methods.

What's wrong with my JavaScript? (C#/ASP.NET)

Here is my JavaScript:
<script type="text/javascript">
function onholdev(index) {
var chk = document.getElementById('<%=grdCons.Rows[' + index + '].FindControl("chkHold").ClientID %>');
var txt = document.getElementById('<%=grdCons.Rows[' + index + '].FindControl("txtReason").ClientID %>');
if (chk.checked == true) {
txt.disabled = false;
}
else {
txt.disabled = true;
txt.value = "";
}
}
</script>
The 'index' variable comes from the RowDataBound event of my GridView, like so:
CheckBox chkHold = ((CheckBox)e.Row.FindControl("chkHold"));
chkHold.Attributes.Add("onchange", "onholdev(" + e.Row.RowIndex + ")");
However, I'm getting 'too many characters in string literal' in the first line of my function (beginning with var chk). Why is this?
You're mixing client and server-side script...you just can't do this. This is executed server-side:
grdCons.Rows[' + index + '].FindControl("chkHold").ClientID
But you're calling it client-side and trying to pass an ID, that's just not something you can do, look at your rendered JavaScript function and this will be much clearer. Instead just use the ID of the table, then you can find your controls that way, for example:
var row = document.getElementById("grdCons").rows[index];
var inputs = row.getElementsByTagName("input");
//then filter by ID match, class, whatever's easiest and set what you need here
That's probably because ASP.NET throws an error, which is written in the client side call of getElementById. The onholdev function is executed client - side, and so cannot pass the index parameter to ASP.NET which is executed server - side. Try this:
<script type="text/javascript">
function onholdev(checkbox, textbox) {
var chk = document.getElementById(checkbox);
var txt = document.getElementById(textbox);
if (chk.checked == true) {
txt.disabled = false;
}
else {
txt.disabled = true;
txt.value = "";
}
}
</script>
Replacing your server - side code with this:
CheckBox chkHold = ((CheckBox)e.Row.FindControl("chkHold"));
chkHold.Attributes.Add("onchange", "onholdev('" +
e.Row.FindControl("chkHold").ClientID + "','" +
e.Row.FindControl("txtReason").ClientID + "')");
The problem is your use of the single quote characters in ' + index + '. Change those to double qoutes and it should work.

Categories