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!
Related
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?
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());
}
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");
}
I've read a few different examples of this, and it seems to be a clear newbie question for those that don't fully understand the asp.net page life cycle, sorry still learning. None of my attempts to fix have panned out.
aspx:
...
<%
for( int j = 0; j < 11; j++)
{
ChildWeightPounds.Items.Add( new ListItem(j.ToString(),j.ToString()));
}
%>
<asp:DropDownList ID="ChildWeightPounds" runat="server" OnSelectedIndexChanged="DropDownListSelected">
<asp:ListItem Value="">-Select-</asp:ListItem>
</asp:DropDownList>
...
<asp:Button ID="InsertButton" runat="server" Text="Submit" OnClick="InsertButton_Click" />
aspx.cs:
protected void InsertButton_Click(object sender, EventArgs e)
{
foreach (Control c in NewPatientForm.Controls)
{
....
if (c is TextBox)
{
TextBox tb = (TextBox)c;
//Expected response:
Response.Write( "field: " + tb.ID + " = " + tb.Text + "<br />");
}
if (c is DropDownList)
{
DropDownList ddl = (DropDownList)c;
//Unexpected response:
//this is not giving me my selected value, but only the top item ("--select--")
Response.Write("field: " + ddl.ID + ", selectedItem: " + ddl.SelectedItem.Value + "<br />");
}
}
}
It's pretty clear this is a IsPostBack, DataBind(), problem with my lack of understanding of the page life cycle. But what doesn't make sense, is i'm iterating through all controls, and textboxes, checkboxes, checkboxlists all work fine, and give me the value in the field, for some reason the dropdownlist doesn't give me the value.
I've tried using the OnSelectedIndexChanged event, I've tried using the DataBind() function, but playing with these, still hasn't gotten me the value.
The biggest issue with your example is you are using inline C# within your page with <% %>. This isn't advised for asp.net. That's more of a legacy/classic ASP approach which won't play well with .NET for many reasons.
Try moving your code that adds the items to the dropdownlist from the markup file into the .cs file, and be sure to hook into a page event that happens at or before OnPreRender. That is the last point you can alter the page controls and have viewstate/lifecycle work correctly.
protected void Page_Load(object sender, EventArgs e)
{
for( int j = 0; j < 11; j++)
{
ChildWeightPounds.Items.Add( new ListItem(j.ToString(),j.ToString()));
}
}
It's likely without running your example that the values are being inserted into the dropdownlist at the incorrect time in the lifecycle, and because of that when you try to access the selected value in the code behind it doesn't work.
Consider the following article on asp.net lifecycle which may assist you.
You can adjust AutoPostBack="true" on your DropDownList, and define OnSelecIndexChanged event
<asp:DropDownList ID="ChildWeightPounds" runat="server"
OnSelectedIndexChanged="DropDownListSelected" AutoPostBack="true>
<asp:ListItem Value="">-Select-</asp:ListItem>
</asp:DropDownList>
Code Behind
void DropDownListSelected(Object sender, EventArgs e)
{
var value = ChildWeightPounds.SelectedValue;
}
I'm binding my gridview's bound columns with datafield using the column name of my datatable. The problem is we have a scenario we need to put in a text where the datafield was int with value 0. I couldn't see any work around. Is there any easy way to do this?
If you don't like to use inline code in your aspx pages as David has suggested make a template with a literal control in it and implement the OnDataBinding event:
For example in your grid have the following template for your field:
<asp:TemplateField HeaderText="Your Header Name">
<ItemTemplate>
<asp:Literal runat="server" ID="litYourCustomField" OnDataBinding="litYourCustumField_DataBinding"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
Then you implement the OnDataBinding in your code behind:
protected void litYourCustomField_DataBinding(object sender, System.EventArgs e)
{
Literal lit = (Literal)(sender);
int yourInt = Convert.ToInt32(Eval("YourNumber"));
lit.Text = (yourInt == 1) ? "It's a 1" : "It's something else";
}
I prefer this method to the inline code since it puts no code in your aspx pages. I usually have a #region defined in my .cs file that has all by databinding code. I am pretty sure performance wise they will be pretty much identical except for maybe the overhead of the literal control if you have the viewstate enable. Make sure to turn off viewstate when you don't need it.
If this is ASP.Net, you can make this a Template column and do the following:
<ItemTemplate>
<%# MyConversionFunction(Convert.ToInt32(DataBinder.Eval(Container.DataItem, "IntegerFieldName"))) %>
</ItemTemplate>
protected string MyConversionFunction(int ValueToCheck)
{
if(ValueToCheck.ToString() == "0")
{
return "SomeText";
}
else
{
return SomeValue.ToString();
}
}