I have a ListBox that contains all the online users.
The users are loaded from a MySQL database and loaded into the ListBox every second.
When I add an Item to the ListBox the ListBox scrolls up, I do not want this to happen.
<asp:UpdatePanel ID="usersPanel" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<asp:ListBox ID="lstUsers" runat="server" ViewStateMode="Enabled" AutoPostBack="True"></asp:ListBox>
<asp:Timer ID="mainTimer" runat="server" ontick="Timer1_Tick" Interval="1000"></asp:Timer>
</ContentTemplate>
</asp:UpdatePanel>
Timer Code:
protected void Timer1_Tick(object sender, EventArgs e)
{
...
MySqlDataReader datareader = command.ExecuteReader();
if (datareader.HasRows) {
lstUsers.Items.Clear();
while (datareader.Read()) {
lstUsers.Items.Add(new ListItem(datareader.GetString(1), datareader.GetInt32(0).ToString()));}
}
}
I've tried to do it with javascript but I was unable to get/set the scrollbar position on the listbox
What is done here is to save the current selected on list on client side, and set it back after the panel have been updated with the new values.
<script type="text/javascript" language="javascript" >
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_beginRequest(beighnloadinf);
prm.add_endRequest(EndRequest);
var selected = "";
//get selected index and store in variable
function beighnloadinf() {
var sel = document.getElementbyId('<%=lstUsers.ClientID%>');
var listLength = sel.options.length;
for(var i=0;i<listLength;i++){
if(sel.options[i].selected){
selected =sel.options[i].value;
break;
}
}
}
// set selected index back afrer update finished
function EndRequest(sender, args) {
var sel = document.getElementbyId('<%=lstUsers.ClientID%>');
sel.value = selected;
}
</script>
You can do the same thing and on code behind, you get the selected one, and place it after the new update of your list.
You shouldn't be clearing the control every second. This is your problem:
lstUsers.Items.Clear();
Simplest solution would be to compare you ListBox items with your data source using the Except method on IEnumerable.
You'll have to convert your data source to IEnumerable manually. See this post as to how to do that.
NOTE: You'll have to change the type for the extension method.
After that, you can loop through your difference set (the returned object for .Except()) and add them to your list box like this:
lstUsers.Items.Add("a new list item");
Related
I have written a code for button click that should retrieve data from the database and display the data row wise as required. It is working Fine for the first two clicks and it is not firing for the third time... I really don't understand why Please any help.
thank you in advance
The button code
protected void NextButton_Click(object sender, EventArgs e)
{
c++; //integer created to iterate through rows of datatable
qno++; //just counts the rows begining from 1 and displays on page
SqlCommand lque = new SqlCommand("select * from questions where course='" + cour + "' and [group]='" + gr + "' and semester='" + sem + "'", con);
IDataReader rque = lque.ExecuteReader();
if (rque.Read())
{
DataTable dt = new DataTable();
dt.Load(rque);
QuestionNo.Text = Convert.ToString(qno);
Question.Text = dt.Rows[c].Field<string>(4);// only displaying the required columns.
RadioButton1.Text = dt.Rows[c].Field<string>(5);
RadioButton2.Text = dt.Rows[c].Field<string>(6);
RadioButton3.Text = dt.Rows[c].Field<string>(7);
RadioButton4.Text = dt.Rows[c].Field<string>(8);
}
}
source code for the button
<asp:Button ID="NextButton" runat="server" Text="Next" Width="111px" OnClick="NextButton_Click" />
i also checked the data is loaded without any errors into the datatable by passing the datatable as a source to the gridview, it shows all the rows in gridview but in the labels the first 2 rows only displaying. I also chekced the counting varible is only increasing 2 times.enter image description here
a few rows from the table that i am retrieving
Your variables(c for example) will be reset to 0 on every request(button-click). Http is stateless. So you need to persist this value somewhere else(i.e. Session, ViewState, Hiddenfield, etc).
For example with Session, which you should only use if this site has not too much traffic:
private int CurrentRowIndex
{
get
{
if (Session["CurrentRowIndex"] == null)
Session["CurrentRowIndex"] = 0;
return (int)Session["CurrentRowIndex"];
}
set => Session["CurrentRowIndex"] = value;
}
protected void NextButton_Click(object sender, EventArgs e)
{
int currentRowIndex = ++CurrentRowIndex;
// maybe you need this also for your other variables
// ...
}
You should also not read all rows if you only want one, you should modify your sql query. If you use MS SQL-Server you could use ROW_NUMBER function to select only the required row from DB.
I have a drop down with checkbox for multiple selections of options. Now whenever i select any checkbox of drop down list then i want to show that option in text box next to drop down list. If i deselect that option then that option should also removed from text box.
I searched a lot but didn't get proper solution.
<td style="padding-top: 10px" colspan="3">
<asp:DropDownCheckBoxes ID="ddlproduct" runat="server" AddJQueryReference="true" UseSelectAllNode="false">
<Style SelectBoxWidth="200" DropDownBoxBoxWidth="200" DropDownBoxBoxHeight="200" />
<Texts SelectBoxCaption="--Select--" />
</asp:DropDownCheckBoxes>
<asp:ExtendedRequiredFieldValidator ID="rfv_ddlproduct" runat="server" ErrorMessage="<b>Required</b>" ControlToValidate="ddlproduct" ForeColor="Red"></asp:ExtendedRequiredFieldValidator>
<asp:TextBox ID="txtselectedproducts" runat="server" Width="573px"></asp:TextBox>
</td>
private void fetchandfillprod()
{
DataSet ds = new DataSet();
ds = DBConf.db_fet("select columnname from tablename with(nolock)");
if (ds.Tables[0].Rows.Count > 0)
{
ddlproduct.DataSource = ds.Tables[0];
ddlproduct.DataTextField = "columnname";
ddlproduct.DataValueField = "columnname";
ddlproduct.DataBind();
}
}
I have used DropDownCheckBoxes.dll for checkbox in dropdownlist.
Refer this link..this is exactly what you are looking for..
http://www.aspsnippets.com/Articles/Multiple-Select-MultiSelect-DropDownList-with-CheckBoxes-in-ASPNet-using-jQuery.aspx..
instead of alert bind the check box selected item to the textbox.
Use SelcetedIndexChanged event, found an example and here is modified code. Also this is going to postback full page, i recommend you to use UpdatePanel with this.
protected void ddlproduct_SelcetedIndexChanged(object sender, EventArgs e)
{
txtselectedproducts.Text ="";
foreach (ListItem item in (sender as ListControl).Items)
{
if (item.Selected){
txtselectedproducts.Text += Item.Text;
}
}
}
if it not work out here is original post.
I am using textbox for searching items from data base and loading them in gridview and
i used custom paging on gridview to show only 25 records per page
and i found java script for searching records on client side as
script>
function filter2(phrase, _id) {
var words = phrase.value.toLowerCase().split(" ");
var table = document.getElementById(_id);
var ele;
for (var r = 1; r < table.rows.length; r++) {
ele = table.rows[r].innerHTML.replace(/<[^>]+>/g, "");
var displayStyle = 'none';
for (var i = 0; i < words.length; i++) {
if (ele.toLowerCase().indexOf(words[i]) >= 0)
displayStyle = '';
else {
displayStyle = 'none';
break;
}
}
table.rows[r].style.display = displayStyle;
}
}
</script>
and calling this as:
<input name="txtTerm" onkeyup="filter2(this, '<%=GridView1.ClientID %>')" placeholder="Search" type="text"/>
this function search record from activated page and obviously searching from whole database will be done on server side and i used asp textbox
but i need onkeyup="filter2(this, '<%=GridView1.ClientID %>')"event in my asp textbox e-g
<asp:TextBox ID="txtSearch" onkeyup="filter2(this, '<%=GridView1.ClientID %>')" placeholder="Search" runat="server" AutoPostBack="True" OnTextChanged="txtSearch_TextChanged" />
but asp didn't allow me to do that..
i need your help to achieve this.
thanks in advance.
EDIT:
I need both searching (client side, server side) in single textbox
because
client side allow searching from loaded page of gridview and
server side allow searching from database on clicking
You could add the client attribute of rendered input control via code behind:
protected void Page_Load(object sender, EventArgs e)
{
txtSearch.Attributes.Add("onkeyup", string.Format("filter2(this,'{0}')",GridView1.ClientID)");
}
EDIT:
After the right comment of #Lukas, we should say that the main problem was the use of <%=GridView1.ClientID %> inline expression inside the textbox webcontrol:
<%= %> will write the string directly to the response-stream, which happens after the server control is constructed, so will be rendered as string and not resolved.
For example:
<asp:Label runat="server" ID="label">test</asp:Label>
<asp:TextBox runat="server" ID="txt" Text="<%# label.ID %>" onkeyup="alert('<%: label.ID %>')"></asp:TextBox>
This is what we have in output:
In my ASP.Net default.aspx, I have dropdown list control and following javascript code
<asp:DropDownList ID="ddlGenres" runat="server" AppendDataBoundItems="True" AutoPostBack="True" DataSourceID="EntityDataSource2" DataTextField="cityID" DataValueField="cityID" OnSelectedIndexChanged="ddlGenres_SelectedIndexChanged" ClientIDMode="Static" >
<script type="text/javascript">
var ddlClientID = '<%=ddlGenres.ClientID%>';
//document.getElementById(ddlGenres)
function SetddlVal(nIndx)
{
//$("#ddlGenres")
var ddlListSelect = document.getElementById(ddlClientID);
ddlList.SelectedIndex = nIndx;
}
</script>
====================================================================
In a external javascript file, I am calling the function SetddlVal.
I debugged the code and the ddlList selectedIndex is successfully changed within the script.
=====================================================================
The issue I am facing is, when the SelectedIndex value is changed in the javascript, The ddlGenres_SelectedIndexChanged code is not being triggered.
Please let me know if I am missing anything.
Thanks
Nate
In javascript the property of an <select> input is selectedIndex not SelectedIndex.
Change your function to this:
function SetddlVal(nIndx)
{
var ddlListSelect = document.getElementById('<%=ddlGenres.ClientID%>');
ddlListSelect.selectedIndex = nIndx;
}
I am having some trouble and after quite a bit of research have been unable to find a solution. I am working in SharePoint Designer 2010 and have an ASP.net dropdown populated by a list. I want to get the index value (e.g. 1) of the selected item from the dropdown list and pass it to the URL used to bring up the EditForm.aspx page. See below, and thank you for any help you can provide!
<script type="text/javascript">
function redirect(url) {
var ddl = document.getElementById('DropDownList1');
alert("HI!");
var index = ddl.selectedIndex;
var value = ddl.options[index].value;
location.href = url + value;
return false;
}
</script>
<asp:LinkButton runat="server" id="LinkButton1"
href="https://chartiscorp.sp.ex3.secureserver.net/Lists/System_Information/EditForm.aspx?id="
onclientclick="javascript:redirect(this.href)">Edit System Info</asp:LinkButton>
<asp:DropDownList runat="server" id="DropDownList1" DataValueField="Title"
DataTextField="Title" DataSourceID="spdatasource1" />
You should use the rendered ID:
var ddl = document.getElementById('<%=DropDownList1.ClientID%>');
and the OnClientClick event of the LinkButton:
<asp:LinkButton onclientclick="...">
To get the index just use
var index = ddl.selectedIndex;
or if you want to get the value use
var value = ddl.options[ddl.selectedIndex].value;
I would suggest doing the redirect in a function, not the HTML attribute. Bringing all together:
<script type="text/javascript">
function redirect(url) {
var ddl = document.getElementById('<%=DropDownList1.ClientID%>'),
index = ddl.selectedIndex,
value = ddl.options[index].value;
location.href = url + value;
return false;
}
</script>
<asp:LinkButton runat="server" id="LinkButton1"
href="../Lists/System_Information/EditForm.aspx?id="
onclientclick="redirect(this.href)">LinkText</asp:LinkButton>
<asp:DropDownList runat="server" id="DropDownList1" DataValueField="Title"
DataTextField="Title" DataSourceID="spdatasource1" />
This jsfiddle shows a demo of the rendered output.