NullReferenceException while using findControl on HTML - c#

while clicking on button it give me an error "System.NullReferenceException: Object reference not set to an instance of an object"
aspx Code
<body>
<form id="form1" runat="server">
<div id="choto">
</div>
<asp:Button ID="btn" runat="server" onclick="btn_Click" Text="Submit" />
</form>
</body>
JS code
<script type="text/javascript">
document.getElementById("choto").innerHTML = "<input name=txt1 type=\"text\" id=\"txt1\" ru" + "nat=\"server\" />";
</script>
C# code
protected void btn_Click(object sender, EventArgs e)
{
// HtmlInputText txt = new HtmlInputText();
HtmlInputText txt = (HtmlInputText)FindControl("txt1");
txt.Value = "Shakeel";
}

Simply put, the input with the id "txt1" is not an ASP.NET control, therefore ASP.NET cannot find it. ASP.NET controls must be defined on the server, or the framework won't know about them.
<body>
<form id="form1" runat="server">
<div id="choto">
<asp:TextBox ID="txt1" runat="server" style="display:none;" />
</div>
<asp:Button ID="btn" runat="server" onclick="btn_Click" Text="Submit" />
</form>
</body>
ASP.NET controls cannot be added via JavaScript, however, they can be made to be invisible/visible using JavaScript.
<script type="text/javascript">
document.getElementById('<%# txt1.ClientID %>').style.display = "block";
</script>

Related

Dynamically Create a specific div with its children in C#

I'm sorry in advance if this seems to be a beginners question and wasted some of your time, but it does really bother me and I would really appreciate it if someone could help.
I'm simply creating a "zone" if you will, where the user inputs a word/sentence which are tasks, and then can check if the task was completed or not and/or if the word/sentence needs to be changed.
So in the end, what I need is a textbox lets say where the user inputs a specific number supposed x, and generates x times this div.
Here is the code (unfortunately I could not post pics since I do not have enough reputation..)
ASP.NET code
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="GMode.tiz.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>whatevz</title>
<link href="StyleSheet1.css" rel="stylesheet" />
<script src="../jquery-1.11.3.min.js"></script>
<script src="../functions.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div class="singleContainer">
<div class="lblPlace">
<asp:Label ID="lbl" runat="server" Text="Input Task"></asp:Label>
<asp:TextBox ID="hi" CssClass="txtBox" runat="server"></asp:TextBox>
</div>
<asp:Button ID="save" runat="server" CssClass="UniversalBtn" OnClick="btnCheck_Click" />
<asp:Button ID="cancel" runat="server" CssClass="UniversalBtn" OnClick="btnCancel_Click" />
<asp:Button ID="edit" runat="server" CssClass="UniversalBtn" />
<asp:Button ID="submit" runat="server" CssClass="BtnSubmit" OnClick="btnSubmit_Click" Text="DONE"/>
</div>
</form>
</body>
</html>
C# code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace GMode.tiz
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnCheck_Click(object sender, EventArgs e)
{
lbl.CssClass = "done";
}
protected void btnCancel_Click(object sender, EventArgs e)
{
lbl.CssClass = "undone";
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (hi.Text == "")
{
lbl.Text = "No Value";
}
else
{
lbl.Text = hi.Text;
}
}
}
}
So basically I want to dynamically create <div class="singleContainer"> with everything inside it x times (x defined by the user).
I'm going about this more on the fact like it's C++. When you can dynamically create an array with a specific number x.
Please tell me if you need more of the code. There are still the css and js files that I did not post.
Thank you,
Jack
I think that for this the best option is to use AngularJS, you can do something like this:
<html>
<head>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.min.js"> </script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular-resource.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular-route.min.js"></script>
<script>
var app = angular.module('app', [])
app.controller('PostsCtrl', function ($scope) {
$scope.change = function (){
$scope.listDivs = [];
for(var i=0;i<$scope.createDiv;i++) {
$scope.listDivs.push(i);
}
}
})
</script>
</head>
<body ng-app='app'>
<div ng-controller='PostsCtrl' class='container'>
<input ng-model='createDiv' ng-change="change()"/>
<ul class='list-group'>
<li ng-repeat="post in listDivs" class='list-group-item'>
<div class="singleContainer">
<div class="lblPlace">
<asp:Label ID="lbl" runat="server" Text="Input Task"> </asp:Label>
<asp:TextBox ID="hi" CssClass="txtBox" runat="server"> </asp:TextBox>
</div>
<asp:Button ID="save" runat="server" CssClass="UniversalBtn" OnClick="btnCheck_Click" />
<asp:Button ID="cancel" runat="server" CssClass="UniversalBtn" OnClick="btnCancel_Click" />
<asp:Button ID="edit" runat="server" CssClass="UniversalBtn" />
<asp:Button ID="submit" runat="server" CssClass="BtnSubmit" OnClick="btnSubmit_Click" Text="DONE"/>
</div>
</li>
</ul>
</div>
</body>
</html>
Put your div into a usercontrol (ascx file).
In your main page add a placeholder:
<asp:PlaceHolder runat="server" ID="PlaceHolder1" />
in code behind you can add your control as often as you want:
yourControl= LoadControl("~/Controls/yourControl.ascx");
PlaceHolder1.Controls.Add(yourControl);

C# ASP.NET Code Behind Loop Show Progress And Status Current Record

I thought this could be easily achieved with Jquery or ASP.NET Ajax but not finding a solution or able to create one. I'm close with the below but not able to return value to lblStatus during loop. Or maybe way to use just Jquery and AJAX.
JQuery
<script src="js/jquery-1.7.min.js" type="text/javascript"></script>
<script>
function validateAdd() {
var myExtender = $find('ProgressBarModalPopupExtender');
myExtender.show();
return true;
}
</script>
HTML
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<ajaxToolkit:ModalPopupExtender ID="ProgressBarModalPopupExtender" runat="server" BackgroundCssClass="ModalBackground" BehaviorID="ProgressBarModalPopupExtender" TargetControlID="hiddenField" PopupControlID="Panel1" DynamicServicePath="" Enabled="True" />
<asp:Panel ID="Panel1" runat="server" Style="display: none; background-color: #C0C0C0;">
<p class="wait">Please wait!</p>
<asp:Label ID="lblStatus" runat="server" Text=""></asp:Label>
</asp:Panel>
<asp:HiddenField ID="hiddenField" runat="server" />
<input type="submit" value="Process Records" id="process" causesvalidation="False" onclick="javascript: return validateAdd();" onserverclick="btnProcess_ServerClick" runat="server" />
</form>
Then on the code behind, do a loop and push status on each loop and then hide process dialog. If I could show progress even better, but just trying to show current record processing.
protected void btnProcess_ServerClick(object sender, EventArgs e)
{
//Example Test Looping Through Slow Process
string[] arr1 = new string[] { "record_one", "record_two", "record_three" };
foreach( string s in arr1)
{
lblStatus.Text = "Processing.." + s;
Thread.Sleep(2000);
}
ProgressBarModalPopupExtender.Hide();
}

How can I prevent C# from redrawing a <div> I used jQuery to show

Scenario: I have a modal-style div that will be shown when the user clicks a button. At the time the div is shown, I need to get some data from the back-end to fill in some fields. Additionally, I'd like to use the jQuery method I use for all my modal windows (fades in the modal div, displays a background div as well as enabling the use of ESC key or "click offs" to close the modal).
It looks something like this:
<asp:ScriptManager ID="sc" runat="server" />
<asp:UpdatePanel ID="updForm" runat="server">
<ContentTemplate>
<h4>Testing jQuery calls combined with code behind actions</h4>
<div class="pad-content">
<asp:LinkButton ID="lnkShowIt" runat="server" OnClick="lnkShowIt_Click" Text="Load Form" OnClientClick="showForm()" />
<asp:Panel ID="pnlPopup" ClientIDMode="Static" runat="server" CssClass="box-modal" style="width:500px;display:none;z-index:1001">
<div class="header">Edit Estimate X</div>
<div class="content">
<div class="window">
<h5>Test Form</h5>
<asp:TextBox ID="tbxTime" runat="server" />
<br />
<asp:TextBox ID="tbxText" runat="server" Width="150px" />
<br />
<asp:LinkButton ID="lnkValidate" runat="server" CssClass="link-button-blue" Text="Validate" OnClick="lnkValidate_Click" />
</div>
</div>
</asp:Panel>
</div>
</ContentTemplate>
</asp:UpdatePanel>
<div id="backgroundPopup"></div>
So ... lnkShowIt calls both the jQuery (which will show pnlPopup) as well as the C# (which will populate tbxTime).
jQuery method actually just calls another method from a common js library I have that does the modal window stuff - I don't think that actual code is the problem but here is the simple function used for this page:
<script type="text/javascript" language="javascript">
function showForm() {
loadPopup('#pnlPopup');
}
</script>
Code behind methods look like this:
protected void lnkShowIt_Click(object sender, EventArgs e)
{
tbxTime.Text = System.DateTime.Now.Second.ToString();
}
protected void lnkValidate_Click(object sender, EventArgs e)
{
if (tbxTime.Text == tbxText.Text)
{
Response.Redirect("DynamicBoxesWithJQuery.aspx?mode=success");
}
else
{
tbxText.Style["border"] = "1px solid red";
}
}
I'm able to generate some level of success by doing the following but it seems like just a major hack and I have to assume there's a better approach:
protected void lnkShowIt_Click(object sender, EventArgs e)
{
tbxTime.Text = System.DateTime.Now.Second.ToString();
ScriptManager.RegisterStartupScript(this, this.GetType(), "OpenEditor", "<script type='text/javascript'>loadPopup('#pnlPopup');</script>", false);
}
protected void lnkValidate_Click(object sender, EventArgs e)
{
if (tbxTime.Text == tbxText.Text)
{
Response.Redirect("DynamicBoxesWithJQuery.aspx?mode=success");
}
else
{
tbxText.Style["border"] = "1px solid red";
ScriptManager.RegisterStartupScript(this, this.GetType(), "OpenEditor", "<script type='text/javascript'>loadPopup('#pnlPopup');</script>", false);
}
}
It seems like it should be easier than this, but the way the UpdatePanel keeps redrawing (and thus resetting the display:none on pnlPopup) is really causing me fits.
Thanks in advance
Solution I just found: putting the LinkButton in its own UpdatePanel and then the form in its own UpdatePanel and making sure the div that is the actual popup box is not in an UpdatePanel at all.
<h4>Testing jQuery calls combined with code behind actions</h4>
<div class="pad-content">
<asp:UpdatePanel ID="updLink" runat="server">
<ContentTemplate>
<asp:LinkButton ID="lnkShowIt" runat="server" OnClick="lnkShowIt_Click" Text="Load Form" OnClientClick="showForm()" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:Panel ID="pnlPopup" ClientIDMode="Static" runat="server" CssClass="box-modal" style="width:500px;display:none;z-index:1001">
<div class="header">Edit Estimate X</div>
<div class="content">
<asp:UpdatePanel ID="updForm" runat="server">
<ContentTemplate>
<div class="window"style="min-width:500px;">
<h5>Here is a Test Form</h5>
<label>Time:</label>
<asp:TextBox ID="tbxTime" runat="server" />
<br />
<asp:Label ID="lblText" AssociatedControlID="tbxText" runat="server" ViewStateMode="Disabled">Text:</asp:Label>
<asp:TextBox ID="tbxText" runat="server" Width="150px" />
<br />
<asp:LinkButton ID="lnkValidate" runat="server" CssClass="link-button-blue" Text="Validate" OnClick="lnkValidate_Click" />
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</asp:Panel>
</div>
Seems to do the trick without any Script Registers from the codebehind

One step process file upload

When a user wants to upload a file (currently there are 4 places in the form that allow for this), they first have to “Choose File” and then they have to click on “Upload”. If they miss the 2nd "Upload" step, there is no indication to them or us.
Is there a way to combine the “two-step” process to a single step (select and upload).
Use this link to know more about it
http://www.c-sharpcorner.com/UploadFile/2b481f/uploading-a-file-in-Asp-Net-web-api/
And you can also use this code
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.9.1.min.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="fileupload1" runat="server" />
<asp:Button ID="btn" runat="server" OnClick="btn_Click" Text="upload" style="display:none" />
</div>
<script type="text/javascript">
var isfirst = true;
$(function () {
$('#<%= fileupload1.ClientID %>').on('change', function (e) {
console.log('change triggered');
$('#<%= btn.ClientID%>').trigger('click'); // trigger the btn button click which i have hidden using style='display:none'
});
});
</script>
</form>
</body>
Code behind
protected void btn_Click(object sender, EventArgs e)
{
//TODO
}

fileupload's upload button works different in IE and Chrome

For those who worked with bootstrap, knows it does not support input type = file, so I hide the asp:fileupload using jQuery (after document ready), and have and for the solution (as you can see from the code
<script type="text/javascript">
$(document).ready(function ()
{
$('#columnSelect').change(function ()
{
getImportColumnOrder();
});
// change file upload style similiar to bootstrap style
//$('#uploader').hide();
$('#uploader').change(function ()
{
var val = $(this).val();
var file = val.split(/[\\/]/);
$('#file').val(file[file.length - 1]);
});
});
function getImportColumnOrder()
{
var order = '';
$('#selectOrer').val('');
$('select', $('#MappingTable')).each(function ()
{
order += $(this).prop('selectedIndex') + ',';
});
$('#selectOrder').val(order.substr(0, order.length - 1));
}
</script>
<div class="span12">
<asp:DropDownList ID="ddl_DBTableList" runat="server" CssClass="combobox" Style="display: inline">
<asp:ListItem></asp:ListItem>
<asp:ListItem Value="Import_Test">Import_Test</asp:ListItem>
</asp:DropDownList>
<asp:FileUpload ID="uploader" runat="server" CssClass="btn" />
<div class="input-append" style="display: inline;">
<input id="file" class="input-medium" type="text" />
<a class="btn" onclick="$('input[id=uploader]').click();">Select File</a>
</div>
<p />
<div>
<asp:Button ID="btn_uplaod" runat="server" OnClick="doUpload" Text="Upload" CssClass="btn" />
</div>
<p />
<asp:Label ID="result" runat="server" ForeColor="Red"></asp:Label>
<p />
<asp:Label ID="data" runat="server" BackColor="#CCCCCC"></asp:Label>
<p />
<asp:Button ID="btn_import" runat="server" Text="Next" OnClick="doImport" OnClientClick="getImportColumnOrder();return true;" Visible="false" CssClass="btn btn-success" />
</div>
Steps are click on the "Select File", a file chooser popped up for file selection. After double clicked a file, the file location gets displayed in , and also the asp fileupload control.
In Chrome and FF, when I clicked btn_uplaod (button), it runs as supposed. In IE, it will clear the fileupload's content and does nothing (a client side action) and will not do any postback.
If this is a program problem, then maybe Chrome and FF will not run correctly. I'm suspecting is there anything that I need to add to make IE run as suppose to?
image after click upload (IE), (Browse link is cleared)
image after click upload (Chrome), (Run as supposed to)
thanks!
I've made a simple version for those of you who wants to try on Visual studio:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="postback_problem.aspx.cs" Inherits="postback_problem" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script> </head> <body> <form id="form1" runat="server"> <div> <asp:FileUpload ID="uploader" runat="server" CssClass="btn" /> <div> <input id="file" class="input-medium" type="text" /> <a onclick="$('input[id=uploader]').click();">Select File</a> </div> <p /> <div> <asp:Button ID="btn_uplaod" runat="server" OnClick="doUpload" Text="Upload" CssClass="btn" /> </div> <asp:Label ID="result" runat="server"></asp:Label> </div> </form> </body> </html>
and
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class postback_problem : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void doUpload(object sender, EventArgs e) { result.Text = "no problem!"; } }

Categories