I have a code here that gets a transaction number on a search bar and show it on the page. I also have 2 textbox wherein the client will enter the price payed and the OR No of the receipt. However, I am getting an error
"Object reference not set to an instance..."
.ASPX
<form id="form1" runat="server">
<div>
<asp:Repeater ID="rptrCashierTable" runat="server">
<ItemTemplate>
<div>
<h1 align="center">Transaction Number: <label><%# Eval("TXNNo") %></label>
<h2>Name:<label><%# Eval("FName") %></label>
<label><%# Eval("MName") %></label>
<label><%# Eval("LName") %></label></h2>
<h2>Contact Number: <label><%# Eval("MOBILE") %></label></h2>
<h2>Product Ordered: <label><%# Eval("PName") %></label></h2>
<h2>Product ID:<label><%# Eval("ProductID") %></label></h2>
<h2>Price:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></h2>
<h2>OR No.:
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox></h2>
<asp:Button ID="Button1" runat="server" Text="Submit" OnClick="btn_Update" />
</div>
</ItemTemplate>
</asp:Repeater>
</div>
</form>
.CS
public partial class TransactionDetails : System.Web.UI.Page
{
SQLQuery sql = new SQLQuery();
DataSet ds = new DataSet();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindCasierTable();
}
}
private void BindCasierTable()
{
string TransctID = Request.QueryString["TXNNo"];
ds = sql.dsGetClientDetails(TransctID);
rptrCashierTable.DataSource = ds;
rptrCashierTable.DataBind();
}
protected void btn_Update(object sender, EventArgs e)
{
foreach (RepeaterItem item in rptrCashierTable.Items)
{
if (item.ItemType == ListItemType.Item)
{
var txtPrice = item.FindControl("TextBox1") as TextBox;
var txtORNo = item.FindControl("TextBox2") as TextBox;
string TXNNo = Request.QueryString["TXNNo"];
ds = sql.dsAddPayment(txtPrice.Text, txtORNo.Text, TXNNo);
txtPrice.Text = string.Empty;
txtORNo.Text = string.Empty;
BindCasierTable();
}
}
}
}
I am using MSSQL 2008 and stored procedure. I just want to update and put the Price payed and OR number to their respective field.
That error message means you are assigning something with null value. I guess the error pops out here:
string TransctID = Request.QueryString["TXNNo"]
you should check if its null first:
if(Request.QueryString["TXNNo"]!=null)
{
// make the assignation here
}
Related
Hi i am busy creating a asp.net project that needs to get three values from the user. I am using a textbox with a range textmode to get these values and the first time the user moves the slider it works perfectly but after that the user can.t adjust any of the textboxes anymore.
I tried using a slider extender but this does not seem to work and only a textbox shows.
my html code to create the textboxes and labels showing the value
body>
<form id="form1" runat="server">
<p>
Quantum 1 Length:
<asp:TextBox ID="txtVal1" runat="server" TextMode="Range" min="1" Max="8" OnTextChanged="txtVal1_TextChanged1" AutoPostBack="True"></asp:TextBox>
<asp:Label ID="lblVal1" runat="server" Text="/////"></asp:Label>
</p>
<p>
Quantum 2 Length:
<asp:TextBox ID="txtVal2" runat="server" TextMode="Range" min="1" Max="8" OnTextChanged="txtVal2_TextChanged1" AutoPostBack="True"></asp:TextBox>
<asp:Label ID="lblVal2" runat="server" Text="/////"></asp:Label>
</p>
<p>
Quantum 3 Length:
<asp:TextBox ID="txtVal3" runat="server" TextMode="Range" min="1" Max="8" AutoPostBack="True" OnTextChanged="txtVal3_TextChanged1"></asp:TextBox>
<asp:Label ID="lblVal3" runat="server" Text="/////"></asp:Label>
</p>
<p>
<asp:Button ID="btnNext" runat="server" AutoPostBack="true" Height="24px" OnClick="btnNext_Click" style="margin-left: 0px" Text="Next" Width="150px" />
<script type="text/javascript" __designer:mapid="129">
function NextPage() {
window.open('Execution.aspx', 'Execution');
}
</script>
<asp:Label ID="lblError" runat="server" ForeColor="Red" Text="Invalid input; Please ensure that Quantum 1 <= Quantum 2 <= Quantum 3" Visible="False"></asp:Label>
</p>
</form>
</body>
My C# code used to control the boxes and change their values
public partial class Quantums : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
try
{
txtVal1.Text = HttpContext.Current.Session["Q1"].ToString();
}
catch { }
try
{
txtVal2.Text = HttpContext.Current.Session["Q2"].ToString();
}
catch { }
try
{
txtVal3.Text = HttpContext.Current.Session["Q3"].ToString();
}
catch { }
lblVal1.Text = txtVal1.Text;
lblVal2.Text = txtVal2.Text;
lblVal3.Text = txtVal3.Text;
//UpdatePanel1.Triggers.Add(new AsyncPostBackTrigger() { ControlID = "btnNext" });
}
protected void txtVal1_TextChanged1(object sender, EventArgs e)
{
HttpContext.Current.Session["Q1"] = txtVal1.Text;
}
And then the same code for textbox 2 and 3. Any suggestions on why the textboxes vaklue keeps resetting and autopostback is enabled on all three buttons.
I just noticed you were missing if(Page.IsPostBack()) return;. Your problem is that every time you change your textbox, the 'Page_Load' event is enacted, then the respective event handler (see page life cycle). So you were setting the text to the sessions, then setting the sessions to the text, effectively doing nothing.
You actually don't need anything for this page in the Page_load method, at least for now. Try the following:
protected void Page_Load(object sender, EventArgs e)
{
}
protected void txtVal1_TextChanged(object sender, EventArgs e)
{
Session["Q1"] = txtVal1.Text;
lblVal1.Text = txtVal1.Text;
}
protected void txtVal2_TextChanged(object sender, EventArgs e)
{
Session["Q2"] = txtVal2.Text;
lblVal2.Text = txtVal2.Text;
}
protected void txtVal3_TextChanged(object sender, EventArgs e)
{
Session["Q3"] = txtVal3.Text;
lblVal3.Text = txtVal2.Text;
}
You can then access the user input values using the respective session values. For example:
protected void Submit(object sender, EventArgs e)
{
List<string> answers = new List<string>();
answers.Add(Session["Q1"].ToString());
answers.Add(Session["Q2"].ToString());
answers.Add(Session["Q3"].ToString());
// Do stuff with answers
}
I am designing a web page in asp.net C# named "myprofile". The structure is as follows from top to bottom: file upload control(for logo), drop down (for hotel type), a rich text box (for contact information - extra: bold, italics, hyperlink etc features), drop down (for location).
My problem is maintaining the values of file upload control and rich text box on postback. Also I am unable to insert the values in database as nothing is happening. I tried many things. Finally, I set my design as follows:
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<fieldset style="width:30%">
<legend>Update Panel-1</legend>
<br />(Type of Hotel)<br /><br />
<asp:DropDownList ID="DropDownTypeOfHotel" runat="server" CssClass="cssdropdown"></asp:DropDownList>
<br />(Contact Information Here)<br /><br />
<asp:TextBox ID="RichTextBoxContactInfo" runat="server"></asp:TextBox>
<br />(Location)<br /><br />
<asp:DropDownList ID="DropDownListLocation" runat="server" CssClass="cssdropdown"></asp:DropDownList>
</fieldset>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<fieldset style="width:30%">
<legend>Update Panel-2</legend>
<asp:Label ID="Label1" runat="server" Text="" ForeColor="Red"></asp:Label>
<br /><br />
<asp:Button ID="btnUpdate2" runat="server" Text="Update Both Panels" OnClick="btnUpdate2_Click" />
</fieldset>
</ContentTemplate>
</asp:UpdatePanel>
My code for the same lies here:-
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
loadHotelType();
}
Page.Form.Attributes.Add("enctype", "multipart/form-data");
}
protected void btnUpdate2_Click(object sender, EventArgs e)
{
if (DropDownTypeOfHotel.SelectedIndex > 0)
{
if (DropDownListLocation.SelectedIndex > 0)
{
if (!string.IsNullOrEmpty(RichTextBoxContactInfo.Text))
{
Label1.Text = "Cool!";
insert();
}
else
{
Label1.Text = "Kindly add contact info!";
}
}
else
{
Label1.Text = "Kindly select location!";
}
}
else
{
Label1.Text = "Kindly select type of hotel!";
}
}
public void loadHotelType()
{
DropDownTypeOfHotel.Items.Insert(0, "--Select Type of Hotel/Supplier--");
DropDownTypeOfHotel.Items.Insert(1, "2 star");
DropDownTypeOfHotel.Items.Insert(2, "3 star");
DropDownTypeOfHotel.Items.Insert(3, "5 star");
DropDownListLocation.Items.Insert(0, "--Select Location of Hotel/Supplier--");
DropDownListLocation.Items.Insert(1, "Canada");
DropDownListLocation.Items.Insert(2, "USA");
DropDownListLocation.Items.Insert(3, "LA");
}
public void insert()
{
int img_logo = 0;
static byte[] btlogo_img;
if (FileUpload1.PostedFile.ContentLength != 0)
{
btlogo_img = new byte[FileUpload1.PostedFile.ContentLength];
HttpPostedFile up1 = FileUpload1.PostedFile;
up1.InputStream.Read(btlogo_img, 0, (int)FileUpload1.PostedFile.ContentLength);
img_logo = 1;
}
if (img_logo == 1)
{
con1.Close();
con1.Open();
SqlCommand cmd = new SqlCommand("insert into file values('" + FileUpload1.PostedFile.FileName + "','" + btlogo_img + "')", con1);
cmd.ExecuteNonQuery();
con1.Close();
}
else
{
Label1.Text = "Kindly select logo!";
}
}
Kindly suggest me with the same.
The easiest solution I found was to keep the controls, that loses value on postback, outside update panel and keep all other controls inside update panel.
It really worked for me!
Have landed into a scenario again. The summary is as follows:
I have a user-control which is basically a mix up of a textbox,imagebuttons,checkboxlist incorporated together to look like a single-select dropdown with checkboxes..works pretty fine. One of the images inside the usercontrol opens up an aspx page as a popup.have few functionalities there viz saving values to database and stuffs.
On the OK button click of the popup page, I should be able to save the values to the DB as well as populate the usercontrol(which acts as a dropdown) with the value which I have saved to the DB.
Here the problem arises, when trying to bind the checkboxlist(present in the usercontrol) to the values from the DB, I get the error that the checkboxlist object is null and has not been created.
I feel that on the OK button click, the usercontrol has to refresh and hence the checkboxlist will be active.
PFB the relevant codes:
Usercontrol.ascx:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="SingleSelectCustomDropDown.ascx.cs" Inherits="MS.IT.Informa.UI.UserControls.SingleSelectCustomDropDown" %>
<asp:Panel ID="panel" runat="server">
<div id="FirstDiv">
<table>
<tr>
<td align="right">
<asp:TextBox ID="txtSelect" runat="server" ReadOnly="true"></asp:TextBox>
</td>
<td>
<asp:Image ID="imgShow" ImageUrl="../Images/DDGlyph.png" onmouseover="this.src='../Images/DDGlyphHOVER.png'" onmouseout="this.src='../Images/DDGlyph.png'" runat="server" />
</td>
</tr>
<tr>
<td colspan="2">
<div id="SecondDiv" style="display:none;">
<asp:CheckBoxList ID="chkBoxList" runat="server">
<asp:ListItem Value="0" Text="Standard" Selected="True"></asp:ListItem>
</asp:CheckBoxList>
</div>
<div id="ThirdDiv" style="display:none;">
<asp:ImageButton ID="btnNew" runat="server" Height="20px" ImageUrl="~/Images/new.png" Width="20px" OnClientClick="ShowPopup();" />
<asp:ImageButton ID="btnEdit" runat="server" Height="20px" ImageUrl="~/Images/edit.png" Width="20px" />
<asp:ImageButton ID="btnDefault" runat="server" Height="20px" ImageUrl="~/Images/default.png" Width="20px" />
<asp:ImageButton ID="btnDelete" runat="server" Height="20px" ImageUrl="~/Images/delete.png" Width="20px" />
</div>
</td>
</tr>
</table>
</div>
</asp:Panel>
<script type="text/javascript">
//Displays the divs containing checkboxlist and images
function ShowList() {
document.getElementById("SecondDiv").style.display = "block";
document.getElementById("ThirdDiv").style.display = "block";
}
//Hides the divs containing checkboxlist and images
function HideList() {
document.getElementById("SecondDiv").style.display = "none";
document.getElementById("ThirdDiv").style.display = "none";
}
//Displays the selected item from the checkboxlist into the textbox placed in the Custom Control
function DisplaySelectedItem(sender, txtBoxID) {
var x = document.getElementById(sender.id);
var chkBoxPrefix = sender.id + "_";
var selectedText;
for (i = 0; i < x.rows.length; i++) {
if(document.getElementById(chkBoxPrefix+i).checked)
{
selectedText = document.getElementById(chkBoxPrefix+i).parentNode.innerText;
}
}
document.getElementById(txtBoxID.id).value = selectedText;
}
//Ensures that only one item is selected from the checkboxlist
function SelectOnlyOneCheckBox(e) {
if (!e) e = window.event;
var sender = e.target || e.srcElement;
if (sender.nodeName != 'INPUT') {
return;
}
var checker = sender;
var chkBox = document.getElementById('<%= chkBoxList.ClientID %>');
var chks = chkBox.getElementsByTagName('INPUT');
for (i = 0; i < chks.length; i++) {
if (chks[i] != checker)
chks[i].checked = false;
}
}
function ShowPopup() {
window.open("ViewColumnOptions.aspx", "ViewColumnOptions", "height=300,width=600,left=300,top=150");
}
</script>
The codebehind for the usercontrol as below:
public partial class SingleSelectCustomDropDown : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
chkBoxList.Attributes.Add("onclick", "SelectOnlyOneCheckBox(event);DisplaySelectedItem(this," + txtSelect.ClientID + ");HideList();");
txtSelect.Attributes.Add("onclick", "ShowList();");
imgShow.Attributes.Add("onclick", "ShowList();");
}
}
public void PopulateOtherViews()
{
SaveReportViewFilter<ReportFilterBase> newObj = new SaveReportViewFilter<ReportFilterBase>();
ViewColumnOptions vwobj = new ViewColumnOptions();
newObj.UserName = vwobj.Page.User.Identity.Name;
SaveReportView<ReportFilterBase> obj2 = new SaveReportView<ReportFilterBase>();
DataTable dt = obj2.GetSaveReportViewFromDataBase(newObj);
chkBoxList.DataSource = dt;//chkBoxList becomes null here..we have ample data in the datatable though
chkBoxList.DataTextField = dt.Columns[0].ToString();
chkBoxList.DataValueField = dt.Columns[0].ToString();
chkBoxList.DataBind();
}
}
The function PopulateOtherViews is called on the button click of the aspx page.
Below is the code:
protected void btnOK_Click(object sender, EventArgs e)
{
if (chkSaveView.Checked)
{
if (!string.IsNullOrEmpty(txtViewName.Text))
{
//some code here to save the view name from txtViewName to the DB
SingleSelectCustomDropDown obj22 = new SingleSelectCustomDropDown();
obj22.PopulateOtherViews();
Page.ClientScript.RegisterStartupScript(this.GetType(),"close","CloseWindow();",true);
}
else
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "alertEnterViewName", "alertMessage('Please enter the view name');", true);
}
}
}
Any help, suggestions, pointers will be greatly appreciated.
Regards
Anurag
In btnOK_Click you are creating a new instance of the user control and not attaching it to the page. My suggestion is:
1.Register the user control and add it to the page.
<%# Register Src="~/UserControl/SingleSelectCustomDropDown.ascx" TagPrefix="uc1" TagName="SingleSelectCustomDropDown" %>
and ...
<uc1:SingleSelectCustomDropDown runat="server" id="obj22" />
2.Now modify in code behind:
protected void btnOK_Click(object sender, EventArgs e)
{
if (chkSaveView.Checked)
{
if (!string.IsNullOrEmpty(txtViewName.Text))
{
//some code here to save the view name from txtViewName to the DB
//Do not create the control again
//SingleSelectCustomDropDown obj22 = new SingleSelectCustomDropDown();
obj22.PopulateOtherViews();
Page.ClientScript.RegisterStartupScript(this.GetType(), "close", "CloseWindow();", true);
}
else
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "alertEnterViewName", "alertMessage('Please enter the view name');", true);
}
}
}
I have a ListView control with DataPager, i am trying to show results from database into ListView the database have field in which i have store content from ajaxhtmlextender i have bind ListView with database like this
protected void ListEvents()
{
conn = new SqlConnection(connSting);
cmdListEvent = new SqlCommand("SELECT * FROM LatestEvents",conn);
table = new DataTable();
conn.Open();
adpter = new SqlDataAdapter(cmdListEvent);
adpter.Fill(table);
ListEvent.DataSource = table;
ListEvent.DataBind();
conn.Close();
}
and the .aspx file
<asp:ListView ID="ListEvent" runat="server"
OnItemDataBound="ListEvent_ItemDataBound" >
<LayoutTemplate>
<asp:PlaceHolder runat="server" ID="itemPlaceholder"></asp:PlaceHolder>
</LayoutTemplate>
<ItemTemplate>
<div class="contmainhead">
<h1 id="evhead"><asp:Label ID="LabelTittle" runat="server"><%#Eval("Tittle") %></asp:Label></h1>
</div>
<div class="contmain">
<asp:Label ID="LabelBody" runat="server"> <%#Eval("Body") %></asp:Label>
</div>
</ItemTemplate>
</asp:ListView>
It is giving the intended results but the problem is the label
<asp:Label ID="LabelBody" runat="server"> <%#Eval("Body") %></asp:Label>
showing all the formatted text and images as html markup, i know to work the label perfectly i have to use this function
Server.HtmlDecode();
i tried it like this
protected void ListEvent_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
Label LabelBody = (Label)e.Item.FindControl("LabelBody");
LabelBody.Text = Server.HtmlDecode(LabelBody.Text);
}
}
But the label shows nothing. . so how can i make the label show the content correctly?
Your help will be greatly appreciated . .Thanx
protected void ListEvent_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
ListViewDataItem dataItem = (ListViewDataItem) e.Item;
Label LabelBody = (Label)e.Item.FindControl("LabelBody");
LabelBody.Text = (string) DataBinder.Eval(dataItem.DataItem, "Body");
}
}
Please make sure there is a column named in your returned datatable
and also remove the <%# EVAL %> tag from the text attribute of your label, leave it empty or do not specify the attribute in your aspx
try
<asp:Label ID="LabelBody" runat="server" text='<%#Eval("Body") %>' />
EDIT :
if the above didn't work try :
<asp:Label ID="LabelBody" runat="server" text="<% #Eval("Body").ToString() %>" />
<asp:Repeater ID="Cartridges" runat="server" onitemcommand="Cartridges_ItemCommand">
<ItemTemplate>
<p class="cartprice"><%#String.Format("{0:C}", Eval("Price"))%></p>
<hr class="hr4" />
<p class="cartqty">QTY <asp:TextBox ID="cartQty" Text="0" runat="server"></asp:TextBox> </p>
<div class="cartbuy2"><asp:LinkButton ID="buy" runat="server" CommandName="AddtoCart" CommandArgument=<%#Eval("cartID") %> Text="Buy"></asp:LinkButton></div>
</ItemTemplate>
</asp:Repeater>
How can I pass the textbox value within CommandArgument? Sorry totally lost...
Did you try: CommandArgument='<%#Eval("cartID") %>'
this is different from yours as it is surrounded by a single quote, I guess this is the correct syntax.
Use FindControl to get other items in the repeater Item. For Example:
protected void repeater_ItemCommand(object sender, RepeaterCommandEventArgs e)
{
LinkButton lb = (LinkButton)e.CommandSource;
string textBoxValue = ((TextBox)lb.Parent.FindControl("cartQty")).Text;
}
you need to bind the cartId to the linkbutton onItemDataBound and then access it onItemCommand, I have modified code for you, give this a go
<asp:Repeater ID="Cartridges" runat="server" onitemcommand="Repeater_OnItemCommand" OnItemDataBound="Repeater_OnItemDataBound">
<ItemTemplate>
<p class="cartprice"><%#String.Format("{0:C}", Eval("Price"))%></p>
<hr class="hr4" />
<p class="cartqty">QTY <asp:TextBox ID="cartQty" Text="0" runat="server"></asp:TextBox> </p>
<div class="cartbuy2"><asp:LinkButton ID="buy" runat="server" CommandName="AddtoCart" Text="Buy"></asp:LinkButton></div>
your onItemdatabound should look like this
protected void Repeater_OnItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
//your code...
LinkButton add = (LinkButton)e.Item.FindControl("buy");
add.CommandArgument = cartID.ToString();
}
and then you can access the text box on item command like this
protected void Repeater_OnItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "AddtoCart")
{
LinkButton btnEdit = (LinkButton)e.CommandSource;
if (btnEdit != null)
{
string editId = btnEdit.CommandArgument;
string text = ((TextBox)e.Item.FindControl("cartQty")).Text;
//do some stuff with your cartid and quantity
}
}
}
You can also extend your code with edit/delete command arguments by adding more linkbuttons and binding them to the correct command and then accessing them in on item command
Thanks