Set ContextKey for AutoCompleteExtender inside GridView - asp.net

I have an AJAX AutoCompleteExtender, in a GridView, as seen below:
<asp:GridView
ID="GV1"
runat="server"
AllowPaging="True"
OnPageIndexChanging="GV1_OnPageIndexChanging"
OnRowCommand="GV1_RowCommand">
...
<asp:TextBox
ID="txt1"
runat="server"
onkeyup = "SetContextKey()">
</asp:TextBox>
<cc1:AutoCompleteExtender
ID="AutoCompleteExtender1"
runat="server"
TargetControlID="txt1"
ServiceMethod="GetACEList"
ServicePath="AutoComplete.asmx"
UseContextKey = "true"
MinimumPrefixLength="1"
EnableCaching="true"
CompletionSetCount="1"
CompletionInterval="100"
CompletionListCssClass="autocomplete_completionListElement"
CompletionListItemCssClass="autocomplete_listItem"
CompletionListHighlightedItemCssClass="autocomplete_highlightedListItem">
</cc1:AutoCompleteExtender>
...
</asp:GridView>
When trying to set the context key, I am unable to access the AutoCompleteExtender on the client side as well as the server side.
On the client-side, I tried:
function SetContextKey() {
$find('AutoCompleteExtender1').set_contextKey($get("<%=ddlCountry.ClientID%>").value);
}
but JavaScript is unable to find the 'AutoCompleteExtender1' object. I realize that this is because there are a lot of 'AutoCompleteExtender1' objects in the generated HTML, each with a unique ID.
I then found this article, and I tried setting the context key on the server side:
protected void ddlCountry_OnSelectedIndexChanged(object sender, EventArgs e) {
AutoCompleteExtender1.ContextKey = ddlCountry.SelectedValue;
}
but the code compilation fails with the error:
The name 'AutoCompleteExtender1' does not exist in the current context
QUESTION:
How do I access the AutoCompleteExtender1 object on selected-index change of the drop down so I can set the context key?

Got it! I fixed how I was accessing the object incorrectly on the server side, and it worked!
Here's the server side code -- on selected-index change of the drop down, I loop through each of the rows of the GridView, and set each AutoCompleteExtender object's ContextKey to the drop-down's selected value:
protected void ddlCountry_OnSelectedIndexChanged(object sender, EventArgs e) {
foreach (GridViewRow gvRow in gvGV1.Rows) {
AjaxControlToolkit.AutoCompleteExtender AutoCompleteExtender1
= (AjaxControlToolkit.AutoCompleteExtender)gvRow.FindControl("AutoCompleteExtender1");
AutoCompleteExtender1.ContextKey = ddlCountry.SelectedValue;
}
}
Hope this helps someone stumbling upon this problem!
P.S:
I gave up trying to achieve the same thing on the client-side. I believe being able to set the Context Key on the server side (in C#) has a lot of advantages in terms of flexibility (like being able to change the context key as and when required, and not just on change of a drop-down). Still, if anyone knows how it can be done on the client-side (in JavaScript), please share.

Below code can be used if you want it to set at HTML end instead of c# code
for (var i = 0; i < grid.rows.length - 1; i++) {
var txtAmountReceive = $("input[id*=txt1]")
var GridRowID = (txtAmountReceive[i].valueOf('id').id).replace("txt1", "");
var AutoCompleteExt = GridRowID + 'AutoCompleteExtender1';
$find(AutoCompleteExt).set_contextKey("1");
}

Related

how to store a label control text into a textbox control value

i am trying to set the value of a textbox control in my aspx page as the value of a label text. I am using the following code but nothing happens. I have tried from the code behind file using c# and then I want to assign the textbox value to a session variable. If I just assign a string value like "Hello"it works, but otherwise nothing works.
protected void btnBook_Click(object sender, EventArgs e)
{
txtmtcid.Text = blbtest.Text;
Session["mtcid"] = txtmtcid.Text;
//Response.Redirect("booknow.aspx");
}
}
I also tried with Javascript, but no use:
var mtcid = parsedData.employeeCode;
document.getElementById('txtmtcid').value = mtcid;
The above js code works fine if I am assigning the value of mtcid to a label text, but not for the text box. please help.
You don't show things that could be messing this up.
and we can't see your markup used.
What does your page load event look like. Keep in mind that EVERY button click, post-back or ANY control on the page with a event code stub WILL RUN the page load event EVERY time. the page load event runs every time, and BEFORE your button click code runs.
So, if I have this markup:
<asp:Label ID="blbtest" runat="server" Text="zoo"></asp:Label>
<br />
<asp:TextBox ID="txtmtcid" runat="server"></asp:TextBox>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Button"
onclick="Button1_Click" />
<br />
And then code behind of this:
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
txtmtcid.Text = blbtest.Text;
}
I then get this when I click on the button
So, we can see how the lable text is now copy to the text box.
You have to post more markup, and give futher detilas (such as some grid view, repeater or any other boatload of features that well explain your issue).
Note that you can double click on the button in the web forms designer to create a event click for the button. Its possible that no event code for the button exists, and your button click code and code behind never runs.
So this is the markup:
<asp:Label ID="blbtest" runat="server" ClientIDMode="Static">
</asp:Label>
<asp:Button ID="btnBook" runat="server" Text="Book Now"
CssClass="spaces-info__button" OnClick="btnBook_Click"/>
<asp:TextBox ID="txtmtcid" runat="server">
</asp:TextBox>
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!(Session["username"] == null))
{
string usn = Session["username"].ToString();
lblusn.Text = usn;
}
}
protected void btnBook_Click(object sender, EventArgs e)
{
txtmtcid.Text = blbtest.Text;
Session["mtcid"] = txtmtcid.Text;
Response.Redirect("booknow.aspx");
}
updated js:
$(function () {
//dom is ready
var request = new XMLHttpRequest;
var usn = document.getElementById('lblusn').innerHTML;
//var usn = "juhaina.ahmed";
console.log(usn);
request.open('GET', "URL" + usn + ""); //of course I have replaced
the URL here
request.onload = function () {
var response = request.response;
var parsedData = JSON.parse(response);
console.log(parsedData);
var nm = parsedData.fullName;
document.getElementById('lblfullnm').innerHTML = nm;
var mtcid = parsedData.employeeCode;
document.getElementById('blbtest').innerHTML = mtcid;
document.getElementById('txtmtcid').value =
document.getElementById('blbtest').innerHTML
};
request.send();
});
I am new to js, and asp.net, so trying to browse whatever possible and work things out here. The session variable value is just not getting passed to next page. Honestly, i dont need the textbox, I dont know if label text can be stored in session variables. If thats possible, then all I want to do is assign the blbtest label text to the session variable, but that also didnt work,but if I am hard coding it like:
Session["mtcid"]="D-11234"
this works and the value of session variable is passed.
hence I am trying now with textbox. Please let me know if theres a better approach to this.
If there is a way to avoid the use of the label and textbox and simply pass the session variable, Session["username"] from the code behind to the javascript, that would be great. how can I do it?

Facing error both DataSource and And DataSourceID are defined on GridView Entity Framework

i am using entity frame work and want to bind data on Grid View but facing problem i have code that i am pasting as well as attaching screen shot i also saw answer regarding this problem but not beneficial for me so any one have experience with this error must be appreciated.
aspx.cs Code
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
lblMessage.Text = "";
}
void BindGrid()
{
using (GapEntities1 context = new GapEntities1())
{
if (context.Organizations.Count() > 0)
{
// GdvOrganization is a gridview ID name
GdvOrganization.DataSource = context.Organizations;
GdvOrganization.DataBind();
}
}
}
Seems like you are trying to bind the GridView from Markup side (.aspx ) as well as using code behind.( .aspx.cs )
Choose any one way only to bind the grid.
1.) If you bind gridview from code behind then remove the DataSourceId property from grid view from markup. Change below code:
<asp:gridview id="GdvOrganization" runat="server" autogeneratecolumns="False"
DataSourceID="MyDataSource">
to
<asp:gridview id="GdvOrganization" runat="server" autogeneratecolumns="False">
2.) if you prefer to bind from markup side then you have to remove the c# code to bind the grid.
Still if above 2 steps doesn't interest you, try below trick ( Recommended ?? )
GdvOrganization.DataSource = ds;
GdvOrganization.DataSourceID = String.Empty;
GdvOrganization.DataBind();

First letter disappears on Ajax Toolkit AutoCompleteExtender

My CompletionInterval is 100 and MinimumPrefixLength is 1. Sometimes after typing one letter that I know has completions, like 'a', after roughly one second, maybe less (but 1 second is a specified time), that initial 'a' disappears. When I type another one, I get a list of completions? Does anyone know what is going on here? I'm using v7.0607 of the AjaxControlToolkit that brings v1.4.6 of the HtmlAgilityPack with it.
My AutoCompleteExtender and associates look like this:
<asp:HiddenField runat="server" ClientIDMode="Static" ID="autoCompleteHidden" OnValueChanged="autoCompleteHidden_ValueChanged" />
<asp:TextBox ID="txtSearchField" runat="server" Width="200px"></asp:TextBox>
<ajaxToolkit:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" TargetControlID="txtSearchField"
ServicePath="~/AutoComplete.asmx" ServiceMethod="GetVisitors" Enabled="False" CompletionInterval="100"
MinimumPrefixLength="1" CompletionSetCount="30" OnClientItemSelected="OnAutoCompleteSelected"
CompletionListCssClass="CompletionList" CompletionListItemCssClass="CompletionListItem"
CompletionListHighlightedItemCssClass="CompletionListHighlightedItem">
</ajaxToolkit:AutoCompleteExtender>
NOTE: Enabled is set to True before this control group is used and back to False afterwards. That is NOT the problem.
The accompanying function script, below, works fine.
<script type="text/javascript">
function OnAutoCompleteSelected(source, eventArgs) {
$("#autoCompleteHidden").val(eventArgs._text);
__doPostBack("autoCompleteHidden", "");
}
</script>
That script triggers the following code-behind handler that fetches the details for the selected visitor. It also works fine:
protected void autoCompleteHidden_ValueChanged(object sender, EventArgs e)
{
var myVisitorObj = new XTime.OL.VisitorObj();
myVisitorObj = XTime.BL.myVisitor.SelectVisitorByFullName(autoCompleteHidden.Value);
if (myVisitorObj.MST_SQ != 0)
{
XTime.XTimeVariables.VisitorObj = myVisitorObj;
}
ddlSearchBy.SelectedIndex = 0;
AutoCompleteExtender1.Enabled = false;
//Need to reload page for Sessions variable to change
Response.Redirect(Request.Url.ToString());
}

ASPxGridview get row data from server-side

I'm working on a DevExpress Gridview and I want to get the data of the selected row (only one row can be selected at the time). I'm working on the Server-Side and I'm using FocusedRowChanged function.
EDIT: The FocusedRowChanged fire but nothing happen and the textboxes do not change value
protected void dxgrDepartement_FocusedRowChanged(object sender, EventArgs e)
{
Page.ClientScript.RegisterClientScriptBlock(GetType(), "FetchData", "<script language='javascript'>FetchData('4654654646')</script>");
txtDescription.Text = "patate";
//txtComments.Text = dxgrDepartement.GetRowValues(dxgrDepartement.FocusedRowIndex, "IdDepartment").ToString();
}
And the "FetchData :
function FetchData(text) {
//ClearField();
document.getElementById("<%= txtDescription.ClientID %>").value = text.toString();
}
BTW - Changing the callbacks property made no difference for us. We needed callbacks for other functionality so couldn't turn this off anyway.
The GetRowValues method did not work either.
This is a technique described on DevExpress' web site and it worked for us as long as we didnt use DevExpress' controls (ASPxDateEdit, ASPxTextBox):
ASPX page:
<dxwgv:GridViewDataTextColumn Caption="Dist. %" FieldName="DistributionPerc" VisibleIndex="3"
Width="50px">
<DataItemTemplate>
<asp:TextBox ID="txtDistPerc" runat="server" Text='<%# Eval("DistributionPercent") %>'
Width="50px" />
</DataItemTemplate>
</dxwgv:GridViewDataTextColumn>
Code behind:
for (int i = 0; i < grdHistory.VisibleRowCount; i++)
{
TextBox textbox = grdHistory.FindRowCellTemplateControl(i, grdHistory.Columns["DistributionPerc"] as GridViewDataColumn, "txtDistPerc") as TextBox;
var anything = textbox.Text;
}
Use:
gridView.GetRowValues(gridView.FocusedRowIndex, columnFieldName1, columnFieldName2, ..., columnFieldNameN)
Method ASPxGridView.GetRowValues
Property ASPxGridView.FocusedRowIndex
grid.EnableCallback = false; solved my problems!

Clearing the value of ASP.Net 2.0 File Upload Control using javascript that works on all browser?

We are running following javascript function:
function btn_AddToList_Click() {
var filePath = document.getElementById("FileUpload").value;
if(filePath.length > 0)
{
var opt = new Option(filePath,filePath);
var listBox = document.getElementById("ListBox");
listBox.options[listBox.options.length] = opt;
}
}
Function binding:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
btn_AddToList.Attributes.Add("onclick", "btn_AddToList_Click(); return false;");
}
}
HTML:
asp:FileUpload ID="FileUpload" runat="server" Width="394px"
asp:ListBox ID="ListBox" runat="server" Width="394px"
asp:Button ID="btn_AddToList" runat="server" Enabled="true" Text="Add"
Issue is that value of "FileUpload" is not get cleared after we click "Add" button. Any help?
You can not set/clear the value of FileUpload control programmatically. That is a restriction for a security reason. Consider this if this restriction was not there, you could set the value of FileUpload control to some arbitrary file and upload it to your server. You won't be able to achieve this in current shape.
As a work around you can try to bring another textbox exactly on top of textbox part of FileUpload control. This way you will be give the same feeling what you are trying to achieve. But that is also not ideal and may not work properly.

Resources