Saba Tt
Saba Tt

Reputation: 13

Action Attribute

I want to send form data to aspx.cs page view below codes.

But this error generated:Object reference not set to an instance of an object.

Please guide me.

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>



 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


 <html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

  <title></title>

  </head>

<body>

 <form id="form1" runat="server" method="post" action="Default2.aspx">

<input id="Text1" type="text" value="dgfdh"  runat="server" name="Text1"/>
</form>
</body>

</html>

 protected void Page_Load(object sender, EventArgs e)
{
    TextBox1.Text = Request.Form["Text1"].ToString();

}

Upvotes: 1

Views: 322

Answers (3)

Lea Cohen
Lea Cohen

Reputation: 8190

When you are running the page for the first time, there is no form yet (the aspx side is created after the cs part is run), and therefore Request.Form has no fields yet.

Since the values of the form will be sent only upon submit (for example when clicking on a "Submit" button), you should put your assignment in a condition that checks if we've gotten to the page upon submit:

protected void Page_Load(object sender, EventArgs e)
{
    if (IsPostBack){
         TextBox1.Text = Request.Form["Text1"].ToString();
    }

}

Upvotes: 2

Vir
Vir

Reputation: 1354

As your Design View i don't see any control with the ID TextBox1 so please first create a control with the Following id and then go for

TextBox1.Text = Request.Form["Text1"].ToString();

you can also do this like

protected void Page_Load(object sender, EventArgs e)
{
    TextBox TextBox1=new TextBox();

    TextBox1.Text = Request.Form["Text1"].ToString();

}

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1499770

When you load the page for the first time, there won't be any form values yet, because none will have been sent from the client. So Request.Form["Text1"] will be null.

Perhaps you should check Page.IsPostBack first? Ideally you should always validate that you've got all the form values you expect before using them anyway, of course.

It's not clear why you're calling ToString() in the first place though - the expression Request.Form["Text1"] is already a string isn't it? Can't you just use:

TextBox1.Text = Request.Form["Text1"];

You should check what happens if you set the Text property to null though. You could always use the null coalescing operator to fix that:

TextBox1.Text = Request.Form["Text1"] ?? "";

Upvotes: 1

Related Questions