Gridviewcell to textbox not working - c#

I have the following working so far in C# on my Gridview called GridView1. It works when I put it in the onSelectedIndexChanged.
HostTextbox.Text = GridView1.SelectedRow.Cells[0].Text;
but since this posts back to the server I want to avoid it because I will be doing it for cells[0] to cells[10]. So, I looked into Javascript. I googled around and found various solutions and this is the one I have "semi-working" so far.
My C# looks like this:
int myRowIdx = 0; // class variable
protected void OnRowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("ondbclick", "sample('" + myRowIdx.ToString() + "')");
}
myRowIdx++;
}
In my Javascript I inserted alerts to tell me where the problem happpens. It looks like this:
function sample(rowIn) {
alert("A");
var gViewID = '<%= GridView1.ClientID %>';
alert("B");
var gView = getElementById(gViewID);
alert("C");
var gViewRow = gView.rows[rowIn];
alert("D");
var gViewRowColumn = gViewRow.cells[0];
alert("E");
var displayCell = gViewRowColumn.innerText;
alert("F");
alert(displayCell);
}
B is the last alert I see. I can't seem to figure this out. I looked carefully into it and still no success. Please help.

I don't understand what you mean with "I want to avoid it because I will be doing it for cells[0] to cells[10]". You could do that for each cell in the selected row successively. So you only need one Postback.
According to your Javascript problems, you could simply pass the tr(GridViewRow) as js-variable to your sample-function. Therefore you only have to pass this as parameter:
e.Row.Attributes.Add("ondbclick", "sample(this)");
and in your js-function:
function sample(tr) {
var gViewRowColumn = tr.cells[0];
var displayCell = gViewRowColumn.innerText;
alert(displayCell);
}

Use Item Template Panel for grid view.
ex.http://msdn.microsoft.com/en-us/library/aa479353.aspx
Use the onrowcommand event for get the values.
like..
Event
{
if(e.commandname="Edit")
{
}

Related

Asp.net Custom Table Cell ClientID not set

I have a class derived from WebControls.TableCell.
When the Text property is set, I call a method that dynamically adds asp:Panels and asp:LiteralControls to the Cell. I want to reference these controls in Javascript, so naturally I tried using the ClientId of the panels in my JS functions. However, these controls have no ClientId set (the string is empty). Why is this? How do I force the ClientIds to be set?
As a temporary solution, I set the ClientIDMode to "static" and created the IDs on my own, but this is not satisfactory because it's hard to reference those IDs in JS. Why? If you assign, for example, "12345" to one control, it gets changed on client side to something like "MainContent_123456". This is bad because the "MainContent" part is not fixed; thus I never know for sure what the real Id on the client side will be. Currently, I can get the control with jQuery using $ctrl = $('[id$='12345']');, but this is dirty because it would get any control that has '123456' in its id.
So, back to the original question: how do I get my ClientIds set automatically for my panels in my custom TableCells?
Edit: Code added
protected void Page_Load(object sender, EventArgs e)
{
this.ClientIDMode = System.Web.UI.ClientIDMode.Static;
}
Code in the method that adds the controls to the custom TableCell:
Panel remainingTextPanel = new Panel();
remainingTextPanel.ID = Guid.NewGuid().ToString();
remainingTextPanel.Style["display"] = "none";
LiteralControl remainingText = new LiteralControl(myText.Substring(initialStringLength, myText.Length - initialStringLength));
remainingTextPanel.Controls.Add(remainingText);
this.Controls.Add(remainingTextPanel);
Panel linkBtnPanel = new Panel();
LinkButton lnkBtn = new LinkButton() {Text = "...", OnClientClick = "toggleDynamicText('" + remainingTextPanel.ID + "'); return false;" };
lnkBtn.Font.Bold = true;
linkBtnPanel.Controls.Add(lnkBtn);
this.Controls.Add(linkBtnPanel);
And the JS Code:
function toggleDynamicText(id) {
$ctrl = $('[id$=' + id + ']');
$(document).ready(function () {
$ctrl.toggle(1000);
});
}
Without seeing any code it's difficult to say what's going on but to access your controls using jQuery you can do the following:
$("#<%=myElement.ClientID%>")
This way it doesn't matter what .NET assigns as the ID.

Changing dropdown items text before asp.net autopostback

I am taking over a project in which a client has some annoying issues.
They have a dropdown that autopostbacks on change to place the selected text into a t-sql query. Any value that has an apostrophe is causing an query error due to not being escaped
I do not have access to compiled code, but was hoping to write a quick band-aid fix to on selected changed, before posting replace an apostrophe to a double apostrophe to escape it as it goes into query.
I wrote a javscript ddl.change function that works at changing the text.
This however is not working even though the apostrophe does change into two. I was wondering if someone could help understand why.
I have two thoughts of scenarios causing the issue.
On autopostback, it triggers before javascript change function does, therefore passing the original value before javascript has a change to modify it.
The server side code only understands what it originally placed into the dropdown and therefore no matter how much I manipulate the client code, it will only see what it placed?
Can anyone confirm either of these scenarios?
Help would be appreciated!
EDIT: I REVERSE ENGINEERED THE CODE, YES ITS VERY UGLY (AND SQL INJECTABLE) BUT IS NOT MINE AND I CANNOT MODIFY IT
C# Code
protected void ddls_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.ddls.SelectedIndex == 0)
{
this.pnlA.Visible = false;
}
else
{
this.pnlA.Visible = true;
string text = Common.GetSql("~/Sql/" + this._Conn + "/PropertyAddressReverseSearch.sql", false, true).Split(new char[]
{
Conversions.ToChar(this._Delimiter)
})[4];
text = string.Concat(new string[]
{
"SELECT * FROM (",
text,
") a WHERE StreetName='",
this.ddls.SelectedItem.Text,
"' "
});
this.Bind(this.ddla, text);
this.ddla.Items.Insert(0, new ListItem("I'm not sure of the house number...", Conversions.ToString(-1)));
this.ddla.Items.Insert(0, new ListItem("", Conversions.ToString(0)));
this.map.Visible = false;
}
}
Javscript + Control
<asp:dropdown runat="server" id="ddls" autopostback="true">
<script type="javascript/text">
$(document).ready(function() {
$("select[id$='adsearch_ddls']").change(function() {
var ddlsValue = $("select[id$='adsearch_ddls'] option:selected").text();
ddlsValue = ddlsValue.replace(/'/g,"\'\'");
$("select[id$='adsearch_ddls'] option:selected").text(ddlsValue);
return false;
});
});
</script>
You can not modify (or add/remove) the Select/dropdown list items client-side, and simply get the same server-side items, with ASP.NET Webforms when viewstate is enabled.
Unless you send back the modified items in another way, like for example in this answer where list items are copied to a hidden field:
function SaveList()
{
//Clear the hidden field
var hField = document.getElementById('<%= YourHiddenField.ClientID %>');
hField.value = '' ;
var selectedList = document.getElementById('<%= YourDropDownList.ClientID %>')
for(i = 0; i < selectedList.options.length; ++i)
{
hField.value = hField.value + ',' + selectedList.options[i].value;
}
That is, assuming by "On selected index change calls server side code" you mean a postback is triggered?
Disabling the ViewState will cause other problems (like SelectedIndexChanged not triggering, etc).
You could handle the selection change through your own (AJAX) postback. But the difference between server- and client-side list items would still remain.

Regarding dropdown list selection

I am bit new in asp.net so please forgive me if my question is silly.
Actually I am loading a page(aspx) through window.open. Everything thing is going fine window is coming with the requested page.
This page is having two panels in a same row ie. in two td's.
One panel is for showing data from different kind of source and the other one is for different kind of source.
Now my problem is with this dropdowns. In my page m having around 10 dropdowns, 5 is left side and 5 is for right side.
when I am setting the values to these dropdowns for both side ( left column 5 dropdowns with differnt values and rith column 5 dropdowns with different values).
i have two seperate methods for "selected vlues" for these dropdowns for each side.
Now problem is........whichever method i call last........that values are appearing in the both side of dropdowns. though i used different methods for selecting values.
see the code snippet of the pageload calls...
if (!IsPostBack)
{
// methods for filling all dropdowns-----
FetchData(); // for first side
FetchData_Q2(); // second side
}
private void FetchData()
{
ddlCardType.SelectedValue = "2";
ddlProductType.SelectedValue = "5";
}
private void FetchData_Q2()
{
ddlCardType.SelectedValue = "1";
ddlProductType.SelectedValue = "1";
}
SO here first side(FetchData()) dropdown is also showing the data as like as second side(FetchData_Q2())
HOPE U R GETTING MY PROBLEM.
It would be better if you could post your code.
But as a suggestion, I would say add the dropdownlist in two different reapter controls, then populate the dropdownlist in the ItemDataBound event of the repeater control.
A better alternative would be to use jQuery like this in each td (or your panel):
for(var i = 0;i<5;i++)
{
var options = $("#options");
$.each(data, function() {
options.append($("<option />").val(this.ID).text(this.Name));
});
//append the $("#options") to a parent div
}
where the data could be achieved by using Ajax GET.
If you want to set selected value for dropdownlist, you have to change selectedindex. You can try something like:
private void FetchData()
{
ddlCardType.SelectedIndex = ddlCardType.Items.IndexOf(ddlCardType.Items.FindByValue("2"));
ddlProductType.SelectedIndex = ddlProductType.Items.IndexOf(ddlProductType.Items.FindByValue("5"));
}
private void FetchData_Q2()
{
ddlCardType.SelectedIndex = ddlCardType.Items.IndexOf(ddlCardType.Items.FindByValue("1"));
ddlProductType.SelectedIndex = ddlProductType.Items.IndexOf(ddlProductType.Items.FindByValue("1"));
}

programmatically adding buttons and OnClientClick but still having post back issue

I am trying to hide some divs using Javascript but i think the post back keeps reloading the page.
To make things more complicated my buttons are added programmatically by my code behind.
foreach (string line in thefilters)
{
Button newButton = new Button();
newButton.ID = Convert.ToString(line);
newButton.Text = Convert.ToString(line);
newButton.CssClass = "tblbutton";
//newButton.Attributes.Add("onclick", "hide_div("+newButton.ID+")");
newButton.OnClientClick = "return hide_div('" + newButton.ID + "')";
pnl_left.Controls.Add(newButton);
}
My javascript is located in the header as follows.
<script type="text/javascript">
function hide_div(filter) {
var pnl_right = document.getElementById("pnl_right");
var listofelements = pnl_right.getElementsById("div");
for (var i = 0; i < listofelements.length; i++) {
if (listofelements[i].id.indexOf(filter) == 0) {
document.getElementById(listofelements[i].id).style.display = 'inline';
}
else {
document.getElementById(listofelements[i].id).style.display = 'none';
}
}
return false;
}
I may have issues in the javascript for what i want to achieve but i am confident that if i can stop the postback then i can solve the javascript myself..
Thanks for any suggestions in advance.
You have not showed in which event you are adding controls. But I am assuming from your problem that you are doing this in Page_Load. If yes, try and move in OnInit event.
Second, in Page_Load you need to check
if(!IsPostBack)
{
//your code for adding controls
}
Hope that helps.

Javascript is not called on radiobutton list index change

I have written code for javascript but it is not called any how. I tried to call both form html side and also by assigning attribute from page load event but it is not at all called.
This is the code for my javascript.
function rdbantiplatelet_onClick(thiscontrol, trName) {
alert('hi');
var RB1 = thiscontrol;
var radio = RB1.getElementsByTagName("input");
var trDose = document.getElementById(trName.toString());
// var RB1 = document.getElementById("<%=this.rdbantiplatelet.ClientID%>");
// var radio = RB1.getElementsByTagName("input");
// var tblAntiplatelet = document.getElementById("<%=tblAntiplatelet.ClientID %>");
for (var i = 0; i < radio.length; i++){
if (radio[i].checked){
trDose.style.display = "";
return true;
}
else{
trDose.style.display = "none";
return true;
}
}
return false;
}
This is the code to call javascript written in page_load event..
rdbantiplatelet.Attributes.Add("OnClick", "return rdbantiplatelet_onClick(this,'" + trDose.ClientID.ToString() + "');");
Try an alert() first to make sure your onclick is firing, then try your rdbantiplatelet_onClick() function:
rdbantiplatelet.Attributes.Add("OnClick", "alert('I am working');");
First of all for your reference here is a list of standard html events
http://www.w3schools.com/tags/ref_eventattributes.asp
try adding something like this to the html radiobutton element
onchange="alert('on change fired');"
and
onclick="alert(' on click fired');
so you can make sure you are picking up the right event.
Once you have the right event then replace the alert call to your method
which would be something like this
onchange="rdbantiplatelet_onClick(this, this.parent.id)"
...you might have to change the 'this.parent.id'
Make sure you are running through a good web browser for development FireFox with the firebug plug-in is great for this stuff.
You are add click event to html table that holds radiobuttons. Use script below:
foreach (ListItem item in rdbantiplatelet.Items)
{
item.Attributes.Add("onclick", "return foobar(this);");
}

Categories

Resources