Getting error in ASP.Net page - asp.net

Can you please let me know why the following piece of code is not working, I am getting the error message when the debugger past the variable "strStatus". The error message is: "Object reference not set to an instance of an object." Can you please help. Thanks - Yagya
protected void Button1_Click(object sender, EventArgs e)
{
if (Y0130_chkNew.Checked == true)
{
bool isChecked = true; // This is required for later retrieval.
string strAction = "Reporting";
string strFromRole = ddSelectRole.SelectedValue;
string TxtBoxID = myProject.getTextBox(strAction, strPath);
TextBox txtb = new TextBox();
txtb = (TextBox)Page.FindControl(TxtBoxID);
string strStatus = txtb.Text;
string ddID = myProject.getDropDown(strAction, strPath);
DropDownList ddLst = new DropDownList;
ddLst = (DropDownList)Page.FindControl(ddID);
string strForwardRole = ddLst.SelectedValue;
// Call the function now
my.updateXML(strFromRole, strAction, strStatus, strForwardRole, strPath);
}
}

Page.FindControl(TxtBoxID); returns null what is the reason for your exception. FindControl does not search controls recursively, only in the given NamingContainer.
If the control is not nested in another NamingContainer on the page(f.e. a GridViewRow), there's no reason at all to use FindControl since you could reference it directly:
string strStatus = TextBox1.Text; // assuming TextBox1 is declared on the aspx
If you're using MasterPages the NamingContainer of controls in the ContentPage is not the page but the ContenPlaceHolder:
Cannot find TextBox on Page

You are finding a control using a function and possibly its returning a textbox id which doesnt existin on page . Please try to debug and see what textbox id you are getting from myProject.getTextBox function and if that exist on page .

Final Code:
if (Y0130_chkNew.Checked == true)
{
string TxtBoxID = "Y0140_txtStatus";
TextBox txtb = new TextBox();
txtb = (TextBox)Page.Master.FindControl("ContentPlaceHolder1").FindControl(TxtBoxID);
string strStatus = txtb.Text;
string ddID = "Y0150_ddOwnerRoleAssignment";
DropDownList ddLst = new DropDownList();
ddLst = (DropDownList)Page.Master.FindControl("ContentPlaceHolder1").FindControl(ddID);
string strForwardRole = ddLst.SelectedValue;
}

Related

Capturing the value of dynamically created TextBox and DropDownList in ASP.NET

I am stuck in an issue, tried googling but could not find any solution.
I have created controls dynamically in Page_Load and I have a static button.
When the button is clicked, I need to capture user entry in those controls.
Now when I am trying to access the control using its unique id, error is being returned as the control is not available at runtime. :(
For loop - starts
if (dr["Type"].ToString().Trim() == "DropDown")
{
DropDownList ddl = new DropDownList();
ddl.Id = "ddl" + Convert.ToString(Counter);
ddl.DataTextField = "Text";
ddl.DataValueField = "Value";
ddl.DataSource = ds1;
ddl.DataBind();
ddl.EnableViewState = true;
cell.Controls.Add(ddl);
}
else if (dr["QuestionType"].ToString().Trim() == "TextBox")
{
TextBox txt = new TextBox();
txt.ID = "txt" + Convert.ToString(Counter);
txt.EnableViewState = true;
cell.Controls.Add(txt);
}
row.Cells.Add(cell);
table.Rows.Add(row);
Even if i do a FindControl in Btn_click function, it says that the panel has 0 controls.
var textbox = (TextBox)pnlMidTermFeedback.FindControl("txt5");
textbox is always NULL, although I have a control txt5. I can see it when I do a F12.
Please help.
Dynamically created controls must be recreated on every postback:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Set values and properties of controls specified in markup
...
}
// Create new controls and add them to the panel
...
}
They will then be available in the button event handler, and contain the data entered by the user.

failing to update private fields in Asp.net

I have a private field in the code behind file of Asp.net page that I'm trying to reset but for some reason it doesn't update. this is the field
private double interest = 0;
I then update this field in this method:
protected void DropDownListBanks_SelectedIndexChanged(object sender, EventArgs e)
{
MajesticEntities majesticentities = new MajesticEntities();
var query2 = from bank in
majesticentities.Banks
where bank.Name == DropDownListBanks.SelectedValue
select bank.Interest;
interest = query2.Single().Value;
// Label5.Text = interest.ToString();
// Label5.Text = fees.ToString() + "welcome";
}
When I try to use the field again in a code initiated by a button click I get the original value (0)
Can anyone please explain why this is happening ?
Thanks
You need to save them in an hidden field , textbox , label or in a view state.
ViewState["VSinterest"] = interest;
Then the value will be saved after postback
"after postback " private double interest = 0; " = 0"
Then if you need te value you take it from where you saved it and convert it to what it needs to be

Row is not updating in gridview in asp.net

I am using update commandField in Gridview. the Textbox used in gridview returning old value. the code for this.
string id = ((Label)GridView1.Rows[e.RowIndex].FindControl("Label6")).Text;
string name = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox1")).Text;
string number = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox2")).Text;
string mail = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox3")).Text;
string address = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox4")).Text;
string s = "update contacts set c_name='"+name+"', c_number='"+number+"', c_mail = '"+mail+"', c_address = '"+address+"' where contact_id = "+id+"";
getsqlConnection();
dbConnection.Open();
MySqlCommand cmd = new MySqlCommand(s, dbConnection);
cmd.ExecuteNonQuery();
GridView1.EditIndex = -1;
loadcontacts();
Please Help...
if (!IsPostBack)
{
}
This code at Page Load solved my problem.

retrieve data from gridview in asp.net vb

I've been looking for this a while but I still don't know how I can get data from the selected rouw out of a Gridview in Asp.net vb.
I tried this but then i get this: Object reference not set to an instance of an object.
Dim email As String
email = Gridview1.SelectedRow.Cells(1).Text
You have to call DataBind before:
Gridview1.DataBind();
Dim email As String
email = Gridview1.SelectedRow.Cells(1).Text
try this ...
email = GridView1.CurrentRow.Cells(1).Value.ToString()
Try this,it may work
Dim email As String
email = Gridview1.SelectedRow.Cells(1).Value.ToString()
protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
//Accessing BoundField Column
string name = GridView1.SelectedRow.Cells[0].Text;
//Accessing TemplateField Column controls
string country = (GridView1.SelectedRow.FindControl("lblCountry") as Label).Text;
lblValues.Text = "<b>Name:</b> " + name + " <b>Country:</b> " + country;
}
Refer the below link.
http://www.aspsnippets.com/Articles/How-to-get-Selected-Row-cell-value-from-GridView-in-ASPNet.aspx

template field (button) of the grid executing on page refresh

I have a button as template field in my hierarchical grid and on that button I am updating some data but when user hit the browser refresh button it executes by itself ..whats the solution..
here is my code behind
protected void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if (!Page.IsPostBack)
{
if (e.CommandName == "UpdateBillData")
{
GridViewRow row = ((Control)e.CommandSource).NamingContainer as GridViewRow;
int index = row.RowIndex;
int billgenID = Convert.ToInt32(GridView1.DataKeys[index].Value);
DropDownList ddmonths = (DropDownList)row.FindControl("DDBillingMonths");
TextBox cunit = (TextBox)row.FindControl("txtCurrBillUnits");
TextBox amountbDue = (TextBox)row.FindControl("txtAmountBDueDate");
TextBox advItax = (TextBox)row.FindControl("txtAdvIncomeTax");
TextBox whtax = (TextBox)row.FindControl("txtWholdingTax");
TextBox gst = (TextBox)row.FindControl("txtGst");
TextBox amountafterdd = (TextBox)row.FindControl("txtAmtAfterDD");
TextBox duedate = (TextBox)row.FindControl("txt_BillDueDate");
TextBox billingdate = (TextBox)row.FindControl("txt_BillGenDate");
TextBox remarks = (TextBox)row.FindControl("txtOthers");
//Update Bill Data Procedure
Database db = DatabaseFactory.CreateDatabase();
DbCommand cmd = db.GetStoredProcCommand("sp_Update_GenBill");
db.AddInParameter(cmd, "#gridrowID", System.Data.DbType.Int32);
db.SetParameterValue(cmd, "#gridrowID", billgenID);
db.AddInParameter(cmd, "#bmonth", System.Data.DbType.String, 3);
db.SetParameterValue(cmd, "#bmonth", ddmonths.SelectedValue);
//Execute Stored Procedure
int i = 0;
i = db.ExecuteNonQuery(cmd);
if (i != 0)
{
showalert("Succesfuly Updated...");
}
else
showalert("Error occured while updating...");
}
}
}
My guess is your last postback before each refresh was a control with a command associated with it. When you hit REFRESH in your browser, it actually reposts the command. Try just going to your browser's address field and hitting ENTER. Do you get the same results?

Resources