selected value cleared in postback - c#

I've dynamically bonded select list and when I hit save button then I'm getting value 0 not the selected one.
I'm Using HtmlSelect not Asp:Dropdownlist.
Can anybody help me.?
thanks in advance !!

If you are using html select.,
you use javascript function for change ddl and assign changed ddl value at one hidden field. send that hidden field value to server. Check below code.
function onchangeddl(e) {
var ddl = document.getElementById('ddlid')
for (var i = 0; i < ddl.options.length; i++) {
if (ddl.options[i].text == e.target.options[e.target.options.selectedIndex].text) {
ddl.selectedIndex = i;
ddl.options[i].selectedValue = e.target.options[e.target.options.selectedIndex].value;
ddl.options[i].selected = true;
document.getElementById('<%=hdnfld.ClientID%>').value = e.target.options[e.target.options.selectedIndex].text;
break;
}
}
}
Codebehind.aspx page you have to assign hdnfld value.
I hope its helpful to you.

Related

How to assign value to text box control inside the table column in C# coding file?

I am creating asp.net web form. in that i am creating dynamic tables in which particular column is numeric text box control.
i don't know how to assign and get values from the text box control.. my coding as follow..
for (int i = 0; i < my_DataTable.Rows.Count; i++)
{
HtmlTableRow _Row = new HtmlTableRow();
HtmlTableCell Col = new HtmlTableCell();
Col.InnerText = my_DataTable.Rows[i]["itmCode"].ToString();
_Row.Controls.Add(Col);
Col = new HtmlTableCell();
_Row.Controls.Add(Col);
Col.InnerHtml = "<input type='number' value='0'>";
_Row.Controls.Add(Col);
my_Table.Rows.Add(_Row);
}
In a paricular method, i need to assign the value to the text box control also needs to get the value existing value.. so i try follow as below
var no_1 = my_Table.Rows[0].Cells[1].InnerText;
If i check the no_1, it has the textbox, but i don't know how to access the current value and assign new value..
can anyone help me how to achieve this..
One thing you have to keep in mind while working with Dynamic Controls is that whenever a postback has occurred you will lose the dynamically created controls(as the postback calls the Page_load() event so if you don't have them at the load event they will not be generated and hence will not be displayed.). So, it is always better to re-render the controls in the load event.
So, in order to get the value of the dynamically assigned controls (either HTML or Asp.net) here is how i would do that.
First, create a holder which will be used to store the controls in the page either with runat="server"(So, you can access that control in the backend). In your case, that control is my_Table. Then use the Session/ViewState to keep a track of all the created dynamic controls which can be used re-render the controls with their values as:
To add a new control in the page it would be like this:
var cnt = _findRelated("txtDynamic") + 1; //for all the dynamic text boxes i am using the prefix of txtDynamic just to keep SOC.
var nId = $"txtDynamic-{cnt}";
var _ctrl = new HtmlInputText("Integer")
{
Name = nId,
ID = nId,
//Value="Default Value" //uncomment to assign a default value
};
_ctrl.Attributes.Add("runat", "server");
var row = new System.Web.UI.HtmlControls.HtmlTableRow();
var newCell = new HtmlTableCell();
newCell.Controls.Add(_ctrl);
row.Cells.Add(newCell);
my_Table.Rows.Add(row);
Session.Add(cnt.ToString(), _ctrl); //here i am using session to manage the controls but you can also use the ViewState
In the above code i am using HtmlInputText to generate an <input type="number"></input> with it's constructor taking the type string more can be read at:HtmlInputText.
The _findRelated() method is used to get the number of dynamic text controls appended to the Form. It is defined as:
private int _findRelated(string prefix)
{
string reqstr = Request.Form.ToString();
return ((reqstr.Length - reqstr.Replace(prefix, "").Length) / prefix.Length);
}
To set the value of the dynamically added control we can do something like this(if not assigned at the creation):
var cell = my_Table.Rows[_myTable.Rows.Count-1].cells[0]; //here i have assumed it is in the last row and in the first cell you can change the index to be anything.
var txtDynamic = cell.Controls.OfType<HtmlInputText>().FirstOrDefault();//getting the control
txtDynamic.Value = "<Some thing new>"; //setting the value
Now, to get the assigned the value:
var cell = my_Table.Rows[_myTable.Rows.Count-1].cells[0]; //here i have assumed it is in the last row and in the first cell you can change the index to be anything.
var txtDynamic = cell.Controls.OfType<HtmlInputText>().FirstOrDefault();//getting the control
//now use the .Value property of the control to get the value as:
var nValue = txtDynamic.Value;
And as we know the dynamically added controls will be lost on the postback event then we can create a method which will use the controls stored in the Session and re-render them with their values as:
private void _renderControls()
{
try
{
if (Session.Count > 0)
{
for (int k = 0; k < Session.Count; k++)
{
if (Session[k] != null)
{
var _ctrl = new HtmlInputText("Integer") //you can make it dynamic to add different types of input control
{
Name = ((HtmlInputText)Session[k]).ID,
ID = ((HtmlInputText)Session[k]).ID,
Value = ((HtmlInputText)Session[k]).Value
};
if (_ctrl != null)
{
_ctrl.Attributes.Add("runat", "server");
var row = new System.Web.UI.HtmlControls.HtmlTableRow();
var newCell = new HtmlTableCell();
newCell.Controls.Add(_ctrl);
row.Cells.Add(newCell);
my_Table.Rows.Add(row);
}
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
Now, let's modify the Page_load() event to call this method on every postback as:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
_renderDynamic(); // this method will be called if there is an postback event to re-render the dynamic controls
}
}
Note:
This is just a sample(there can be a lot better approaches out there).
I have used HtmlInputText with property as Integer to create ainput[type="number"].

Hidden field value updated but not showing updated value in codebehind?

I am setting the hidden filed value through JavaScript as below
<script lang="JavaScript" type="text/javascript">
function ChangeVal()
{
var elem = document.getElementById("btnDownloadStream");
if (elem.value == "Start")
{
elem.value = "Stop";
document.getElementById('myHiddenInput').value = "1";
}
else
{
document.getElementById('myHiddenInput').value = "0";
elem.value = "Start";
}
}
I am trying to get hidden field value in code behind. My code is
HiddenField myHiddenInput = (HiddenField)Page.FindControl("myHiddenInput");
var val = myHiddenInput.Value;
Before this line I am calling one function which creates and generates the GetResponseStream(). While doing this I am not able to get the value from server controls. Why?
Becuase Changing the value in javascript will not affect the server side value.
if you want to change a server side value from javascript: You can try the following
// Javascript
var myHidden = document.getElementById("<%:myHiddenId.ClientId%>");
myHidden.value = myJSVariable;
Make sure the myHidden is a server control.
Set Runat="server" attribute to your hidden field as shown below :
<input type="hidden" value="" id="myHiddenInput" runat="server" />
Then update your javascript function as shown below :
function ChangeVal() {
var elem = document.getElementById("btnDownloadStream");
if (elem.value == "Start") {
elem.value = "Stop";
document.getElementById('<%=myHiddenInput.ClientID%>').value = "1";
}
else {
document.getElementById('<%=myHiddenInput.ClientID%>').value = "0";
elem.value = "Start";
}
}
now you can directly access your hidden field value in your code behind without using Page.FindControl as mentioned :
var val = this.myHiddenInput.Value;
Update:
One thing I have noticed that your button is server side button and in your javascript you call
var elem = document.getElementById("btnDownloadStream");
I think it should be
var elem = document.getElementById('<%=btnDownloadStream.ClientId%>')
otherwise you will always get the value of else part
Make sure this is not the case.
well #Vishweshwar Kapse is answered your question.
Place your hidden field in update panel and don't forget to add click event of button in trigger.
This also happens in case you use the UpdatePannel in your page. if this is the case then place the HiddenField inside the UpdatePannel and try again.
You forget about ViewState. If you change data in the hidden field using java script code the ViewState do not get this changes and that's why you cannot get the correct value in code behind.
Make sure your hidden field have runat="server" attribute..

asp.net Hide Specific items in dropdownlist using javascript

I'm using ASP.NET and I'm dynamically filling up my DropDownList.
Here is my code:
DataTable dtList = new DataTable();
dtList.Columns.Add("Name");
dtList.Columns.Add("Type");
foreach (DataDefinitionResponse dr in _dr)
{
if (dr.Type == "Dropdown")
{
string[] strSplit = dr.ListValue.Split('|');
List<string> lst = new List<string>();
foreach (string word in strSplit)
{
DataRow row = dtList.NewRow();
row["Name"] = word;
row["Type"] = dr.Name;
dtList.Rows.Add(row);
}
}
}
ddlFieldList.DataSource = dtList;
ddlFieldList.DataTextField = "Name";
ddlFieldList.DataValueField = "Type";
ddlFieldList.DataBind();
Now I just want to hide a specific item using Javascript when another DropDownList is selected.
I'm not using SelectedIndexChanged here. I must use Javascript.
Please someone help me with this.
Thx
I don't think you will be able to manipulate the DropDownList with JavaScript and "get away with it" because when the page is subsequently posted back to the server ASP .NET will detect that the DropDownList has been "tampered" with and will throw an exception.
There are flags you can set that stop the error but it is unlikely that you will then be able to use the DropDownList in your code-behind.
You would normally achieve what you are trying to do with SelectedIndexChanged (I know you said you didn't want to) and put the control in an UpdatePanel or similar to avoid a full page post-back / refresh.
function Remove()
{
var DropDownList=document.getElementById('<%=DropDownList1.ClientID%>');
alert(DropDownList.value);
for(i=DropDownList.length-1; i>=0; i--)
{
if(DropDownList.options[i].selected)
{
DropDownList.remove(i);
}
}
}

How to enable disable fields using Java Script in Webform

I have created a web page "Default.aspx" in which I have taken fields:
First Name, Last Name, Account Titling, Titling(radio button list), AccountNumber and AccountFormat
under the "Default.aspx" page, I have used a radio button list also, whose values are Yes and No. If I choose Yes, then the following fields visibility should set to false:
First Name, Last Name
If I choose "NO", then the following fields visibility should set to true:
Account Titling, Account number
For this, I have written the below Java Script code in "Default.aspx"
function EnableDisableTaxID() {
if (document.getElementById("<%=rdOpeningSubAccount.ClientID %>") != null) {
var openSubAccountList = document.getElementById('<%= rdOpeningSubAccount.ClientID %>');
var fbo1RadioList = document.getElementById('<%=fbo1RadioButtonList.ClientID %>').value;
var isOpenSubAccount;
if (openSubAccountList != null) {
var openSubAccount = openSubAccountList.getElementsByTagName("input");
for (var i = 0; i < openSubAccount.length; i++) {
if (openSubAccount[i].checked) {
isOpenSubAccount = openSubAccount[i].value;
alert("Print" + isOpenSubAccount);
}
}
}
alert(typeof(isOpenSubAccount));
if (isOpenSubAccount == 'true') {
FirstName.visible = true;
LastName.visible = false;
AccountTitling.visible = true;
lblFirstName.visible=false;
lblLastName.visible=false;
}
else if (isOpenSubAccount == 'false') {
AccountTitling.visible = true;
AccountNumber.visible = false;
lblAccountTitling.visible = true;
lblAccountNumber.visible = false;
}
}
}
However, I am getting the required value from the Radio button list, however, when I go to check if the selected value of the radiobuttonlist is true, then the code above does not work. I dont know what am I missing. I know that directly using the below code will not work:
if (isOpenSubAccount == 'true') {
FirstName.visible = true;
LastName.visible = false;
AccountTitling.visible = true;
lblFirstName.visible=false;
lblLastName.visible=false;
}
Please help as I m stuck here...
For Visible = false;
document.getElementById('FirstName').style.visibility="hidden";
For Visible = true;
document.getElementById('FirstName').style.visibility="visible";
To Enable:
document.getElementById('FirstName').disabled = false;
To Disable:
document.getElementById('FirstName').disabled = true;
Following can be done for
Non Visible
document.getElementById('id-name').style.display='none';
Visible
document.getElementById('id-name').style.display='block';
Disable
document.getElementById('id-name').setAttribute('disabled', 'disabled');
Enable
document.getElementById('id-name').removeAttribute('disabled');
No; document.getElementById will only get the element with the ID you specify (the HTML spec is quite clear that only one element on a page can have a specific ID).
Each radio button has a different ID attribute, but if you look at the HTML source of a page, you will see that all radio buttons in the list have the same NAME attribute. This is what you should use "the name of the radio button".
onclick="GetRadioButtonValue('<%= radiobuttonlist1.ClientID %>')"
function GetRadioButtonValue(id)
{
var radio = document.getElementsByName(id);
for (var j = 0; j < radio.length; j++)
{
if (radio[j].checked)
alert(radio[j].value);
}
}

AspxGridView selection at runtime

I have an aspxGridView on my page, and i create the columns at runtime. I also add CommandColumn with ShowSelectCheckBox set to true. But after i select one row and click a button to get the row values, AspxGridView.Selection.Count returns 0. I create this GridView on AspxButtons Click event also for paging, create the gridView on Page_Init. Here is the code to create the AspxGridView:
Colenter code hereorCollection colorCol = ConfAttributesManager.Instance
.GetColors();
if (colorCol.Count > 0)
{
GridViewDataTextColumn grdColorCodeColumn = new GridViewDataTextColumn();
grdColorCodeColumn.FieldName = "ColorCode";
GridViewDataTextColumn grdDescriptionColumn = new GridViewDataTextColumn();
grdDescriptionColumn.FieldName = "Description";
gv_Attributes.Columns.Clear();
gv_Attributes.Columns.Add(grdColorCodeColumn);
gv_Attributes.Columns.Add(grdDescriptionColumn);
GridViewCommandColumn grdCmdColumn = new GridViewCommandColumn();
grdCmdColumn.ShowSelectCheckbox = true;
grdCmdColumn.VisibleIndex = 0;
gv_Attributes.Columns.Add(grdCmdColumn);
gv_Attributes.DataSource = colorCol;
gv_Attributes.DataBind();
}
I don't know where do i make a mistake?
Thanks for your help.
It seems that you do not specify the ASPxGridView.KeyFieldName property that is required for Row Selection operation:
gv_Attributes.KeyFieldName = "ColorCode";
//gv_Attributes.KeyFieldName = Unique Key Field;

Categories