I have a DataList Control as follows
<asp:DataList ID="DataList1" runat="server" DataKeyField="FruitID" RepeatColumns="2" Width="387px">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" Height="104px" ImageUrl='<%# Eval("ImageUrl") %>' Width="135px" />
<br />
Item ID:
<asp:Label ID="lblItemID" runat="server" Text='<%# Eval("FruitID") %>' />
<br />
FruitName:
<asp:Label ID="lblFruitNameLabel" runat="server" Text='<%# Eval("FruitName") %>' />
<br />
UnitPrice:
<asp:Label ID="lblUnitPriceLabel" runat="server" Text='<%# Eval("UnitPrice") %>' />
<br />
Quantity:
<asp:TextBox ID="txtQuantity" runat="server"></asp:TextBox>
<br />
<br />
</ItemTemplate>
</asp:DataList>
<asp:Button ID="btnAddtoCart" runat="server" onclick="Button1_Click" Text="Add to Cart" />
and in the code behind im using the following code to get the values of the controls inside the DataList control
int id = int.Parse(((Label)DataList1.Controls[0].FindControl("lblItemID")).Text.ToString());
string Name = ((Label)DataList1.Controls[0].FindControl("lblFruitNameLabel")).Text;
double Price = double.Parse(((Label)DataList1.Controls[0].FindControl("lblUnitPriceLabel")).Text.ToString());
int Quantity = int.Parse(((TextBox)DataList1.Controls[0].FindControl("txtQuantity")).Text.ToString());
string Url = ((Image)DataList1.Controls[0].FindControl("Image1")).ImageUrl;
I'm getting the following exception
Input string was not in a correct format.
Exception occurs in the following line
int Quantity = int.Parse(((TextBox)DataList1.Controls[0].FindControl("txtQuantity")).Text.ToString());
I'm very much sure that i'm entering a Integer value to the textbox :)
am I missing something?
Maybe that would be great when you little bit rewrite your code to this
var myQuantity = ((TextBox)DataList1.Controls[0].FindControl("txtQuantity")).Text.ToString();
int Quantity = int.Parse(myQuantity);
and check with Debugger what type is myQuantity. This should help you to locate your issue.
It could be because of the type casting problem, from the number you entered, to integer. Try making it a long data type instead and also make sure that no characters exists in between the string you entered.
try this
int Quantity =Convert.ToInt32(((TextBox)DataList1.Controls[0].FindControl("txtQuantity")).Text.ToString());
<br />
Quantity :
<asp:TextBox ID="txtQuantity" runat="server"></asp:TextBox>
<br />
i saw that u have not make any bind to txtQuantity. And Convert.ToInt32 gives exception because it s null string. i think so
Related
I have some labels inside a DataList which are populated with text from as the DataList is binded with database. Now i want to place the value of Text of asp.net with Session variable.
<asp:DataList ID = "dl_cmt" runat="server">
<ItemStyle CssClass="coment" />
ItemTemplate>
<asp:Label ID="ll" runat="server" Text='<%# %>' />
<asp:Label ID="lblcmt" runat="server" Text='<%#Eval("ecomment")%>' />
<asp:Label ID="lblDate" style=" color:brown; font-family:Cursive; font-size:x-small; " runat="server" Text='<%#Eval("my_date","on {0}") %>' />
</ItemTemplate>
</asp:DataList>
I want to place the text of label ID="ll" with session["userid"]
You can get the value as follows
ll.Text = Session["userid"].ToString();
Another approach:
You can also hide the implementation details from the aspx code with a property
.cs file
public string userid { get { return Session["userid"]; } }
.aspx file
<asp:Label ID="ll" runat="server" Text='<%= userid %>' >
This will work.
<asp:Label ID="ll" runat="server" Text='<%#Session["yourvariable"]%>'/>
I had a login page. once user successfuly logged in, they can view and manage their profile/information. This would be done by retrieving data from database and display on a formview.
However this following error appeared inside my userprofile.aspx.cs file:
Exception Details: System.IndexOutOfRangeException: An SqlParameter with ParameterName '#UserId' is not contained by this SqlParameterCollection.
Source Error:
Line 44:
Line 45: // Assign the currently logged on user's UserId to the #UserId parameter
Line 46: e.Command.Parameters["#UserId"].Value = currentUserId;
Line 47:
Line 48: }
Userprofile.aspx:
<asp:FormView ID="FormView1" runat="server"
DataSourceID="SqlDataSource1" DataKeyNames="UserId">
<EditItemTemplate>
UserId:
<asp:Label ID="UserIdLabel1" runat="server" Text='<%# Eval("UserId") %>' />
<br />
Password:
<asp:TextBox ID="PasswordTextBox" runat="server"
Text='<%# Bind("Password") %>' />
<br />
Email:
<asp:TextBox ID="EmailTextBox" runat="server" Text='<%# Bind("Email") %>' />
<br />
HomeTown:
<asp:TextBox ID="HomeTownTextBox" runat="server"
Text='<%# Bind("HomeTown") %>' />
<br />
HomepageUrl:
<asp:TextBox ID="HomepageUrlTextBox" runat="server"
Text='<%# Bind("HomepageUrl") %>' />
<br />
Signature:
<asp:TextBox ID="SignatureTextBox" runat="server"
Text='<%# Bind("Signature") %>' />
<br />
<asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True"
CommandName="Update" Text="Update" />
<asp:LinkButton ID="UpdateCancelButton" runat="server"
CausesValidation="False" CommandName="Cancel" Text="Cancel" />
</EditItemTemplate>
<InsertItemTemplate>
UserId:
<asp:TextBox ID="UserIdTextBox" runat="server" Text='<%# Bind("UserId") %>' />
<br />
Password:
<asp:TextBox ID="PasswordTextBox" runat="server"
Text='<%# Bind("Password") %>' />
<br />
Email:
<asp:TextBox ID="EmailTextBox" runat="server" Text='<%# Bind("Email") %>' />
<br />
HomeTown:
<asp:TextBox ID="HomeTownTextBox" runat="server"
Text='<%# Bind("HomeTown") %>' />
<br />
HomepageUrl:
<asp:TextBox ID="HomepageUrlTextBox" runat="server"
Text='<%# Bind("HomepageUrl") %>' />
<br />
Signature:
<asp:TextBox ID="SignatureTextBox" runat="server"
Text='<%# Bind("Signature") %>' />
<br />
<asp:LinkButton ID="InsertButton" runat="server" CausesValidation="True"
CommandName="Insert" Text="Insert" />
<asp:LinkButton ID="InsertCancelButton" runat="server"
CausesValidation="False" CommandName="Cancel" Text="Cancel" />
</InsertItemTemplate>
<ItemTemplate>
UserId:
<asp:Label ID="UserIdLabel" runat="server" Text='<%# Eval("UserId") %>' />
<br />
Password:
<asp:Label ID="PasswordLabel" runat="server" Text='<%# Bind("Password") %>' />
<br />
Email:
<asp:Label ID="EmailLabel" runat="server" Text='<%# Bind("Email") %>' />
<br />
HomeTown:
<asp:Label ID="HomeTownLabel" runat="server" Text='<%# Bind("HomeTown") %>' />
<br />
HomepageUrl:
<asp:Label ID="HomepageUrlLabel" runat="server"
Text='<%# Bind("HomepageUrl") %>' />
<br />
Signature:
<asp:Label ID="SignatureLabel" runat="server" Text='<%# Bind("Signature") %>' />
<br />
</ItemTemplate>
</asp:FormView>
</p>
<p>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:SecurityTutorialsConnectionString %>"
onselecting="SqlDataSource1_Selecting"
SelectCommand="SELECT UserProfiles.UserId, aspnet_Membership.Password, aspnet_Membership.Email, UserProfiles.HomeTown, UserProfiles.HomepageUrl, UserProfiles.Signature FROM aspnet_Membership INNER JOIN UserProfiles ON aspnet_Membership.UserId = UserProfiles.UserId">
</asp:SqlDataSource>
</p>
<p>
</p>
</asp:Content>
Userprofile.aspx.cs:
protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
// Get a reference to the currently logged on user
MembershipUser currentUser = Membership.GetUser();
// Determine the currently logged on user's UserId value
Guid currentUserId = (Guid)currentUser.ProviderUserKey;
// Assign the currently logged on user's UserId to the #UserId parameter
e.Command.Parameters["#UserId"].Value = currentUserId;
}
Create a new SqlParameter and add it to the collection.
SqlParameter param = new SqlParameter("#UserId", currentUserId);
e.Command.Parameters.Add(param);
Try the following:
DbParameter param = e.Command.CreateParameter();
param.ParameterName = "#UserId";
param.Value = currentUserId;
e.Command.Parameters.Add(param);
I didn't test this though
You must add the parameter with
e.Command.Parameters.AddWithValue("#UserId", currentUserId);
Once you have added it you could access it through the indexer as in your example.
UPDATE
If you are working with the System.Data.Common namespace, the AddWithValue method is not available. You will have to do something like
var param = e.Command.CreateParameter("#UserId", currentUserId);
e.Command.Parameters.Add(param);
This is a little bit more complicated but has the advantage that you do not have to implicitly create a parameter of a specific type like SqlParamter or OleDbParameter.
If you already have the parameter listed in your SqlDataSource, then simply point to it and change it's value ...
e.Command.Parameters["#UserId"].Value = currentUserId;
You do not need to create a parameter, unless you have not listed it back in your ASP page.
In below data list represents set of question's and answer, How to check whether the user selected right answer radio button or not when the user clicks on submit button using javascript ?
the answer is stored in database.
Datalist:
<asp:DataList ID="DataList1" runat="server" DataKeyField="Qno"
DataSourceID="SqlDataSource1">
<ItemTemplate>
Qno:
<asp:Label ID="QnoLabel" runat="server" Text='<%# Eval("Qno") %>' />
<br />
Question:
<asp:Label ID="QuestionLabel" runat="server" Text='<%# Eval("Question") %>' />
<br />
<asp:RadioButton ID="RadioButton1" runat="server" Text='<%# Eval("Ans1") %>' />
<br />
<asp:RadioButton ID="RadioButton2" runat="server" Text='<%# Eval("Ans2") %>' />
<br />
<asp:RadioButton ID="RadioButton3" runat="server" Text='<%# Eval("Ans3") %>' />
<br />
<asp:RadioButton ID="RadioButton4" runat="server" Text='<%# Eval("Ans4") %>' />
<br />
<asp:Button ID="Button2" runat="server" Text="Submit" />
<br />
</ItemTemplate>
</asp:DataList>
Provide a CommandName parameter for the Button2 in the DataList: CommandName="Validate"
Add the OnItemCommand event for the DataList1: *OnItemCommand="DataList1_OnItemCommand"*
In the code behind, fill-in the *DataList1_OnItemCommand* event actions:
protected void DataList1_OnItemCommand(object sender, DataListCommandEventArgs e)
{
if (String.Equals(e.CommandName, "Validate"))
{
DataListItem dataItem = (DataListItem )e.Item;
RadioButton rbtn1 = (RadioButton)dataItem.FindControl("RadioButton1");
RadioButton rbtn2 = (RadioButton)dataItem.FindControl("RadioButton2");
RadioButton rbtn3 = (RadioButton)dataItem.FindControl("RadioButton3");
RadioButton rbtn4 = (RadioButton)dataItem.FindControl("RadioButton4");
// Code to check which radio button was checked.
if(rbtn1 != null && rbtn1.Checked)
{
}
else if(rbtn2 != null && rbtn2.Checked)
{
} //Perform these for the remaining two check boxes
}
}
Take required actions based on which check box is checked.
Solved: I used handlers. Thanks btw.
http://www.aspdotnetcodes.com/Insert_Images_Database.aspx
How can I display my image inside the DataList1?
I don't have a clear idea of databinding and such. I hope you guys can help. Thanks
This is my code for my ASPX
<asp:DataList ID="DataList1" runat="server" DataSourceID="SqlDataSource1">
<ItemTemplate>
itemID:
<asp:Label ID="itemIDLabel" runat="server" Text='<%# Eval("itemID") %>' />
<br />
Cloth ID:
<asp:Label ID="Cloth_IDLabel" runat="server" Text='<%# Eval("[Cloth ID]") %>' />
<br />
Style:
<asp:Label ID="StyleLabel" runat="server" Text='<%# Eval("Style") %>' />
<br />
Size:
<asp:Label ID="SizeLabel" runat="server" Text='<%# Eval("Size") %>' />
<br />
Color:
<asp:Label ID="ColorLabel" runat="server" Text='<%# Eval("Color") %>' />
<br />
Image 1:
<asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("[Image 1]") %>' />
<br />
Image 2:
<asp:Image ID="Image2" runat="server" ImageUrl='<%# Eval("[Image 2]") %>' />
<br />
Price:
<asp:Label ID="PriceLabel" runat="server" Text='<%# Eval("Price") %>' />
<br />
Notes:
<asp:Label ID="NotesLabel" runat="server" Text='<%# Eval("Notes") %>' />
<br />
Alignment of Image 1:
<asp:Label ID="Alignment_of_Image_1Label" runat="server"
Text='<%# Eval("[Alignment of Image 1]") %>' />
<br />
Alignment of Image 2:
<asp:Label ID="Alignment_of_Image_2Label" runat="server"
Text='<%# Eval("[Alignment of Image 2]") %>' />
<br />
</ItemTemplate>
</asp:DataList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:TPSConnectionString %>"
SelectCommand="SELECT CustomizedOrder.userid, CustomizedOrder.itemID, ClothInventory.clothID AS [Cloth ID], ClothInventory.style AS Style, ClothInventory.size AS Size, Color.color AS Color, CustomizedOrder.image1 AS [Image 1], CustomizedOrder.image2 AS [Image 2], CustomizedOrder.itemPrice AS Price, CustomizedOrder.notes AS Notes, Alignment.description AS [Alignment of Image 1], Alignment_1.description AS [Alignment of Image 2] FROM CustomizedOrder INNER JOIN ClothInventory ON CustomizedOrder.clothID = ClothInventory.clothID INNER JOIN Color ON ClothInventory.colorID = Color.colorID INNER JOIN Alignment ON CustomizedOrder.alignment1 = Alignment.alignmentID INNER JOIN Alignment AS Alignment_1 ON CustomizedOrder.alignment2 = Alignment_1.alignmentID WHERE (CustomizedOrder.userid = #userid)">
<SelectParameters>
</SelectParameters>
</asp:SqlDataSource>
and this is for the aspx.cs
public partial class addtoShoppingCart : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
MembershipUser User = Membership.GetUser();
object UserGUID = User.ProviderUserKey;
SqlDataSource1.SelectParameters.Add("userid", UserGUID.ToString());
SqlDataSource1.DataBind();
}
}
Asp:Image.ImageUrl expects an URL value, hence if Image1 is a string containing the URL of the image your code should work.
On the contrary, if Image1 is the image itself, then you'll need to temporarily save it on the server and provide the Asp:Image control with the URL for the saved file (check this example for generating the URL)
if you don't have image url from database and you have image datatype in your sql then this code will help to generate image from sql database!
If image path stored in database: ~/Images/file-name.jpg
=> image url in datalist:
ImageUrl='<%# Eval("[ImagePath]") %>' />
i to get the clientid of the control which is placed inside the Edit item template of the gridview in javascript without going to the server side code..
<asp:TemplateField HeaderText="FromDate" SortExpression="FromDate">
<ItemTemplate>
<asp:Label ID="FromDate" runat="server" Text='<%#((DateTime)DataBinder.Eval(Container.DataItem,"FromDate")).ToShortDateString()%>'></asp:Label>
<asp:HiddenField ID="ID" runat="server" Value='<%#Eval("ID") %>' />
<asp:HiddenField ID="ApproveLeaveID" runat="server" Value='<%#Eval("ApproveLeaveID") %>' />
<asp:HiddenField ID="hidLevel3" runat="server" Value='<%#Eval("Level3ManagerACENumber") %>' />
</ItemTemplate>
<EditItemTemplate>
<table>
<tr>
<td>
<asp:TextBox ID="txtFDate" runat="server" Text='<%#((DateTime)DataBinder.Eval(Container.DataItem,"FromDate")).ToShortDateString()%>'>
</asp:TextBox>
<asp:HiddenField ID="ID" runat="server" Value='<%#Eval("ID") %>' />
<asp:HiddenField ID="ApproveLeaveID" runat="server" Value='<%#Eval("ApproveLeaveID") %>' />
<asp:HiddenField ID="hidLevel3" runat="server" Value='<%#Eval("Level3ManagerACENumber") %>' />
</td>
<td>
<a onclick="showCalendarControl(3,<%# Container.ItemIndex %>)">
<img id="img3" runat="server" alt="Clock" src="../Images/clock_add.png" style="border: none" /></a>
</td>
</tr>
</table>
</EditItemTemplate>
<ItemStyle HorizontalAlign="Left" />
<HeaderStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="ToDate" SortExpression="ToDate">
<ItemTemplate>
<asp:Label ID="ToDate" runat="server" Text='<%#((DateTime)DataBinder.Eval(Container.DataItem,"ToDate")).ToShortDateString()%>'>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<table>
<tr>
<td>
<asp:TextBox ID="txtTDate" runat="server" Text='<%#((DateTime)DataBinder.Eval(Container.DataItem,"ToDate")).ToShortDateString()%>'>
</asp:TextBox>
</td>
<td>
<a onclick="showCalendarControl(4,<%# Container.ItemIndex %>)">
<img id="img4" runat="server" alt="Clock" src="../Images/clock_add.png" style="border: none" /></a>
</td>
</tr>
</table>
</EditItemTemplate>
<ItemStyle HorizontalAlign="Left" />
<HeaderStyle HorizontalAlign="Center" />
</asp:TemplateField>
This is my java script:
function showCalendarControl(ControlNo,index) {
var textField;
if(ControlNo==1)
{
textField=document.getElementById('<%=txtFromDate.ClientID%>');
}
else
{
textField=document.getElementById('<%=txtToDate.ClientID%>');
}
if(ControlNo==3)
{
textField=document.getElementsByClassName('txtFDate')[index];
}
if(ControlNo==4)
{
textField=document.getElementsByClassName('txtTDate')[index];
}
calendarControl.show(textField);
}
first two textbox(txtFromDate,txtToDate) is for the not in the grid control...
You can fetch the elements in the ItemDataBound event of the grid (using FindControl), and then pass the ClientID of the textbox as a parameter to showCalendarControl:
TextBox txtFDate = e.Item.FindControl("txtFDate") as TextBox;
TextBox txtTDate = e.Item.FindControl("txtTDate") as TextBox;
HtmlAnchor link = e.Item.FindControl("aLink") as HtmlAnchor;
if (txtTDate != null && txtFDate != null && link != null)
{
link.Attributes.Add("onclick", String.Format("showCalendarControl({0}, '{1}', '{2}')", 4, txtFDate.ClientID, txtTDate.ClientID);
}
(you'll also need to add an ID and a runat="server" to your link. I'm also assuming txtFDate is declared in your EditTemplate although it's not there. The ControlNo parameter could be a data key instead of a constant as in the example, it's not really clear what it is)
Then, in your function, use the clientID parameters to get the textboxes:
function showCalendarControl(ControlNo, txtFDateClientID, txtTDateClientID) {
var textField;
if(ControlNo==3)
{
textField=document.getElementById(txtFDateClientID);
}
if(ControlNo==4)
{
textField=document.getElementById(txtTDateClientID);
}
calendarControl.show(textField);
}
The problem is that every control should have unique server ID. So server side controls which are placed inside template are rendered multiple times with different auto generated ids based on ID you've specified in the template. You can easily see it if you will have a look on the generated html. Therefore your js code is accessing only the html element with hardcoded id. As I guess it is placed in the first row.
Simple solution is to describe your text box in a following way
<asp:TextBox ID="txtTDate" runat="server" CssClass="txtTDate" Text='<%#((DateTime)DataBinder.Eval(Container.DataItem,"ToDate")).ToShortDateString()%>'>
</asp:TextBox>
Then modify the js function in the following way :
function showCalendarControl(ControlNo, index) {
var textField;
if(ControlNo==3)
{
textField=document.getElementsByClassName('txtFDate')[index];
}
if(ControlNo==4)
{
textField=document.getElementsByClassName('txtTDate')[index];
}
calendarControl.show(textField);
}
And modify your link as the following :
<a onclick="showCalendarControl(4, <%# Container.DataItemIndex %>)">
Updated the answer
DataItemContainer has DataItemIndex property which has to be used in this case.