Get value of ASP:TextBox when clicking an ASP:Button - html

I know this is a stupid question, and a simple question, but I feel like I'm going crazy as I can't get this working (even though I've done it a million times before).
I have a text box and a button in my ASP.NET page
<asp:TextBox ID="commentTextBox" inputtype="text" runat="server" CssClass="uk-textarea"></asp:TextBox>
<asp:Button ID="buttonComment" runat="server" CssClass="uk-button uk-button-text" text="Post Comment" OnClick="buttonComment_Click" />
These are a part of a larger set of HTML markup, that is wrapped in a:
<form id="form1" runat="server">
On button click, I do the following (get the value of the text box and post it to a database as a 'comment')
protected void buttonComment_Click(object sender, EventArgs e)
{
try
{
//string commentText = ((TextBox)FindControl("Comment")).Text;
string strDate = Request.Form["commentTextBox"].ToString();
Spark.Comment comment = new Spark.Comment
{
CommentByEmail = Context.User.Identity.Name.ToString(),
CommentDate = DateTime.Now,
SparkId = sparkId,
CommentText = strDate,
};
using (var client = new AmazonLambdaClient(Amazon.RegionEndpoint.APSoutheast2))
{
var request = new InvokeRequest
{
FunctionName = ConfigurationManager.AppSettings["lambdaArnPrefix"] + "lambdaSparkCreateComment",
Payload = JsonConvert.SerializeObject(comment),
InvocationType = InvocationType.RequestResponse
};
var response = client.Invoke(request);
}
Response.Redirect($"SparkDetail?action=comment");
}
catch (Exception ex)
{
sparkCardSingle.Text = ex.ToString();
}
}
I've tried all these variations of getting the value:
string commentText = ((TextBox)FindControl("commentTextBox")).Text
string commentText = Request.Form["commentTextBox"].ToString();
string commentText = CommentText.Text;
But no matter what, I get this error on post back
System.NullReferenceException: Object reference not set to an instance of an object. at APISpark.SparkDetail.Page_Load(Object sender, EventArgs e) in C:\Users\jmatson\Source\Repos\Production-Spark-Website\APISpark\SparkDetail.aspx.cs:line 136
I don't understand. I feel like I've done this code a billion times before and it works. I have no idea why it's not working now.

Related

How can I solve "Object reference not set to an instance of an object"?

This is page load where I make two columns in data table and also connect database with dropdown-list:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[2] { new DataColumn("product_name"), new DataColumn("Quantity") });
ViewState["sales"] = dt;
GridView1.DataBind();
txt_productname.DataSource = sic.get_product_name_for_textbox();
txt_productname.DataTextField = "product_name";
txt_productname.DataValueField = "product_id";
txt_productname.DataBind();
txt_customername.DataSource = sic.get_customer_name_for_textbox();
txt_customername.DataTextField = "customer_name";
txt_customername.DataValueField = "customer_id";
txt_customername.DataBind();
}
Code side this is a temporary data grid:
protected void btn_insert_Click(object sender, EventArgs e)
if (string.IsNullOrWhiteSpace(txt_productname.Text) ||string.IsNullOrWhiteSpace(txt_quantity.Text))
{
Response.Write("<script LANGUAGE='JavaScript'>alert('NotAllowNull') </script>");
}
else
{
DataTable dt = null;
if (Session["DataTable"] != null)
dt = (DataTable)Session["DataTable"];
else
{
}
dt.Rows.Add(txt_productname.SelectedValue.ToString());
dt.Rows.Add(txt_quantity.Text);
GridView1.DataSource = dt;
GridView1.DataBind();
Session["DataTable"] = dt;
}
}
Error:
An exception of type 'System.NullReferenceException' occurred in
Security Managment System.dll but was not handled in user code
Additional information: Object reference not set to an instance of an
object.
Apply breakpoints to the flow of methods and check step by step where your values are set to be null. If there is any null in your code then this error message appears. Apply breakpoint on Post back method. Check data table is properly filled or not. Or you're assigning values aren't null.

Partial View of search module gives " insufficient stack to continue executing the program safely"

I have been stuck in this problem for a while now, and tried solutions suggested by other questions asked on Stackoverflow.
So, basically I have created a search module for my website, which works fine when called by its Url and returns a result. However, when I use it throught its partial view on the main layout page, it gives this error:
"Error executing child request for handler
'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper'"
and later on converted into:
"Insufficient stack to continue executing the program safely. This can
happen from having too many functions on the call stack or function on
the stack using too much stack space."
Here is the code of Controller
public ActionResult SearchResult()
{
return View();
}
[HttpPost]
public ActionResult SearchResult(String h)
{
string s = Request.Form["name"];
var dataContext = new AutonomousEntities();
var saleRepository = new Repository<Sale>(dataContext);
var brandrepository = new Repository<Brand>(dataContext);
string result="";
List<Sale> sd = new List<Sale>();
IEnumerable<Sale> SaleList = saleRepository.GetAll();
IEnumerable<Brand> BrandList = brandrepository.GetAll();
List<Sale> sales = SaleList.ToList();
for (int i = 0; i <SaleList.Count(); i++)
{
Sale t = sales.ElementAt(i);
string name=t.Promotion.Promotion_Name;
if (name.Contains(s))
{
sd.Add(t);
}
}
return View("GetAllSale",sd);
}
This is my View:
#{
Layout = null;
}
#using (Html.BeginForm("SearchResult","Search",FormMethod.Post))
{
<input name="name" style="margin-top:20px;" type="text" />
<input type="submit" style="color:#1FABBC;" value="Search" />
}
And this is the layout page's line on which error is coming:
<span> #Html.Action("SearchResult", "Search")</span>
I have already tried removing [HttpGet] and layout=null

Update text block from downloaded text file = RPC_E_WRONG_THREAD WP8.1

I am learning Windows Phone 8.1 development, I have probably done something utterly incorrectly programming wise
The need: I want to download a text file from the web using HttpClient() and display it in the TextBlock1
From variety of tutorials I have found the following:
public async void DownloadDataAsync()
{
string data = "some link to Textfile.txt";
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(data);
HttpContent content = response.Content;
string result = await content.ReadAsStringAsync();
UpdateTextBlock1(result);
}
Then the other functions.
public void UpdateTextBlock1(string result)
{
TextBlock1.Text = result;
}
private void BtnDownloadData_Click(object sender, RoutedEventArgs e)
{
Task t = new Task(DownloadDataAsync);
t.Start();
}
The code starts well enough - on button pressed, I receive RPC_E_WRONG_THREAD.
Is it that I'm trying to call the method when all threads haven't finished? How can I code that efficently so the TextBlock1 is updated with txt data?
Thanks for understanding, baby steps here in programming, and I couldn't find a relevant answer over google. (Maybe I don't yet know how to ask?)
You need to update the textblock on the UI thread like so:
Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
TextBlock1.Text = result;
});
There are many posts on this subject.

Existing posts keep on re-added into jTable with newer post

Here are my codes :
public void submitReply(ActionEvent e) {
String replyBy = userName;
String reply = jTextArea_reply.getText();
if (reply.equals("")) {
JOptionPane.showMessageDialog(null, "Comment cannot leave blank");
} else {
eForumTopics comment = new eForumTopics(replyBy, reply);
if (comment.createComment() == true) {
JOptionPane
.showMessageDialog(null,
"Reply submitreted successfully. You will be redirect to main page.");
SetUpJTableComment();
public void SetUpJTableComment() {
// Get jTable model
DefaultTableModel tableModel1 = (DefaultTableModel) jTableComment
.getModel();
// Store column data into Array (3 columns)
String[] data = new String[3];
// Set Up Database Source
db.setUp("IT Innovation Project");
String sql = "Select reply_content,reply_by from forumReplies WHERE reply_topic = "
+ topicId + "";
ResultSet resultSet = null;
// Call readRequest to get the result
resultSet = db.readRequest(sql);
try {
while (resultSet.next()) {
data[0] = resultSet.getString("reply_content");
data[1] = resultSet.getString("reply_by");
// Add data to table model
tableModel1.addRow(data);
}
resultSet.close();
} catch (Exception e) {
System.out.println(e);
}
// add tablemodel to jtable
}
The problem is whenever users post a new reply, the existing posts will be re-added together. I try to do like only the newer reply from the comment box will be added into the jTable instead of keep on re-add the existing posts with newer reply. What am I supposed to use? A for loop? Thanks in advance.
The correct way to delete the content of DefaultTableModel is
model.setRowCount(0);
vs. the evil way mentioned in the comment (won't repeat it here ;-) which violates two rules
never change the underlying datastructure of a model under its feet
never call any of the model's fireXX from code outside the model
If doing the latter seems to help, it's a waring signal: you either violated the former or your model implementation is incorrect

Webservices object reference not set to an instance of an object error

I have to make a call to the web service (JSON) to authenticate the user who is trying to login to the app. I have the following xml provided
<summary>
http://geniewebsvc.cloudapp.net/Member.svc/Authenticate
</summary>
<param name="payload">
{"UserName":"testuser#somedomain.com","Password":"p#$$w0rd"}
</param>
<requiredHeaders>
Content-Type: application/json;charset=UTF-8
</requiredHeaders>
<returns></returns>
[OperationContract]
[WebInvoke(UriTemplate = "/Authenticate", Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
AuthenticateResponse Authenticate(AuthCredentials usernamePassword);
There is similar one to check if the userid is already registered and that is a Get method. That works fine and i receive the right response for both successful and unsuccessful cases. But all the post methods are the ones which are giving me trouble. and i noticed that there is one more difference in these xmls.. i.e., the .. the isregistered webservice param tag goes something like this..
<param name="emailAddress"></param>
and here is my get() and post() please let me know whats my mistake...
public void Post()
{
RequestState myRequestState = new RequestState();
try
{
System.Uri uri = new Uri(url);
HttpWebRequest myHttpWebGetRequest;
Logger.log(TAG, "Create a HttpWebrequest object to the URL", url);
myHttpWebGetRequest = (HttpWebRequest)WebRequest.Create(uri);
_mHttpWebRequest = myHttpWebGetRequest;
myRequestState.conn = this;
myRequestState.request = myHttpWebGetRequest;
myRequestState.request.ContentType = "application/json;charset=UTF-8";
myRequestState.request.Method = "POST";
myRequestState.request.AllowReadStreamBuffering = false;
myRequestState.request.Headers["UserName"] = "rick.labarbera#gmail.com";
myRequestState.request.Headers["Password"] = "125124514";
// myRequestState.request.Headers["MemberId"] = "UdE8IwmTbxEjmzmMo2nBpg==";
IAsyncResult result = (IAsyncResult)myHttpWebGetRequest.BeginGetResponse(new AsyncCallback(RespCallback), myRequestState);
}
catch (Exception e)
{
close(myRequestState);
if (this.listener != null)
{
Logger.log(TAG, "post()", e.Message);
}
}
}
public void Get()
{
RequestState myRequestState = new RequestState();
try
{
System.Uri uri = new Uri(url);
HttpWebRequest myHttpWebPostRequest;
Logger.log(TAG, "Create a HttpWebrequest object to the URL", url);
myHttpWebPostRequest = (HttpWebRequest)WebRequest.Create(uri);
_mHttpWebRequest = myHttpWebPostRequest;
myRequestState.conn = this;
myRequestState.request = myHttpWebPostRequest;
myRequestState.request.Method = "GET";
myRequestState.request.AllowReadStreamBuffering = false;
IAsyncResult result = (IAsyncResult)myHttpWebPostRequest.BeginGetResponse(new AsyncCallback(RespCallback), myRequestState);
}
catch (Exception e)
{
close(myRequestState);
if (this.listener != null)
{
Logger.log(TAG, "get()", e.Message);
}
}
}
Am i doing something wrong???All these things are very very new to me.. I need help badly..
Thanks :)
I have played a bit with your code, but couldn't make it :(
What are the URL's you are using for the POST() method and for GET() methods.?
By the way, There is another way around to invoke your service. Follow these steps:
-- Create a new project.
-- Right-click on the Project name and click on "Add Service Reference"... Then provide address as "http://geniewebsvc.cloudapp.net/Member.svc" and click Go.
-- Once service information is downloaded, provide Namespace something like "MyMemberService" and click Ok.
Then Goto your MainPage.xaml.cs and write the following code.
MemberServiceClient client = new MemberServiceClient();
client.AuthenticateCompleted += new EventHandler<AuthenticateCompletedEventArgs>(client_AuthenticateCompleted);
client.AuthenticateAsync(new AuthCredentials() { UserName = "rick.labarbera#gmail.com", Password = "125124514" });
And the AuthenticateCompleted handler is
void client_AuthenticateCompleted(object sender, AuthenticateCompletedEventArgs e)
{
MessageBox.Show(e.Result.Successful.ToString());
}
This way you can simply call any service in the MemberService with just 2 or 3 lines of code. This is how a soap client is invoked in a Visual Studio project.
But again, there are some "Endpoint configuration" issues in this which you need to solve. And if you can do that you can save atleast 30 to 40 % of your development time.
Good luck.