I am wanting to create a session in an URL and assign its value from a database.
For example i currently have URL creating a list according to the select statement.
I am wanting to include Favourite_ID but assign it to a session instead.
So something like: Session ["Fav"] = Favourite_ID;
ASP.
<asp:DataList ID="DataList1" runat="server" ShowFooter="False" ShowHeader="False" Width="460px" CellPadding="1" Height="193px">
<ItemStyle Font-Bold="False" Font-Italic="False" Font-Overline="False" Font-Strikeout="False" Font-Underline="False" />
<ItemTemplate>
<table class="auto-style2">
<tr>
<ul>
<td class="auto-style3">
<h6><li><asp:HyperLink Runat ="server" NavigateUrl ='<%#"RecipePage?id=" + DataBinder.Eval(Container.DataItem, "Recipe_ID").ToString()%>' ID="Hyperlink1"><%#DataBinder.Eval(Container.DataItem, "Recipe_Name")%></asp:HyperLink></asp></li></h6>
</td>
</ul>
</tr>
</table>
</ItemTemplate>
C#
private void loadRecipe()
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0; AttachDbFilename=C:\Users\Donald\Documents\Visual Studio 2013\Projects\DesktopApplication\DesktopApplication\Student_CB.mdf ;Integrated Security=True");
con.Open();
try
{
//Fetching top recipe
string query = ("SELECT * FROM Recipe LEFT JOIN Favourite on Recipe.Recipe_ID = Favourite.Recipe_ID WHERE Favourite.Student_ID = '"+UserID.Text+"' ORDER BY Recipe_Name");
SqlDataAdapter da = new SqlDataAdapter(query, con);
DataSet ds = new DataSet();
da.Fill(ds);
DataList1.DataSource = ds;
DataList1.DataBind();
}
catch (Exception)
{
//catch exception here
}
con.Close();
}
Also im just testing what i can do at the moment. So excuse the bad practise of not using a parameter and using Try-catch.
This will change once i understand whether i can use a session the way im hoping to.
I have used changed my current code to allow the use of a CommandArgument. In which calls and creates a session.
<asp:DataList ID="DataList1" runat="server" ShowFooter="False" ShowHeader="False" Width="460px" CellPadding="1" Height="193px">
<ItemStyle Font-Bold="False" Font-Italic="False" Font-Overline="False" Font-Strikeout="False" Font-Underline="False" />
<ItemTemplate>
<table class="auto-style2">
<tr>
<ul>
<td class="auto-style3">
<h6><li><asp:LinkButton runat="server" OnCommand="Call_Fav" CommandArgument='<%# Eval("Favourite_ID") %>' ID="bob" Text='<%#DataBinder.Eval(Container.DataItem, "Recipe_Name")%>' /></li></h6>
</td>
</ul>
</tr>
</table>
</ItemTemplate>
Related
I was coding for my project which I am working on currently and had the need to
Add courses and batch to courses
Delete courses on demand
using gridview for the same.
I am using OnRowCommand event, the deletion works fine,entry is being deleted from database too, but for some reason, this error is being thrown:
"The GridView 'gvCourses' fired event RowDeleting which wasn't handled."
Note:- I am not using 'OnRowDeleting' in the aspx file.
Here is the odd thing which I, as a beginner do not understand. The error does not show up anymore when I generate the 'OnRowDeleting' event and leave the event blank in code behind behind(0 lines of code inside the event handler).
Looking to learn and understand why it is happening. Any help would be greatly appreciated.
.aspx code:
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:Panel ID="Panel2" runat="server">
<table style="width:100%;">
<tr>
<td style="width:210px">
</td>
<td>
</td>
</tr>
<tr>
<td style="width:210px"> </td>
<td> </td>
</tr>
<tr>
<td style="width:210px; height: 331px;"></td>
<td style="height: 331px">
<asp:GridView ID="gvCourses" runat="server"
AutoGenerateColumns="False"
CssClass="table-hover table"
GridLines="None" Width="800px"
ShowFooter="True"
OnRowCommand="gvCourses_RowCommand" >
<Columns>
<asp:BoundField DataField="course"
HeaderText="Courses in Valsura"
SortExpression="DateField" />
<asp:TemplateField>
<FooterTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem>Select</asp:ListItem>
<asp:ListItem>Students</asp:ListItem>
<asp:ListItem>Teachers</asp:ListItem>
</asp:DropDownList>
<asp:Button ID="Button1" runat="server"
OnClick="Button1_Click"
Text="Add Course"
CssClass="btn-danger" />
</FooterTemplate>
<ItemTemplate>
<asp:LinkButton ID="LinkButton2"
runat="server">View Batches</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="LinkButton3"
runat="server"
CommandName="delete"
CommandArgument='<%#Eval ("course") %>'>Delete</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:RequiredFieldValidator ID="rfvCourse"
ControlToValidate="DropDownList1"
InitialValue="Select"
ErrorMessage="Select*"
ForeColor="Red" >
</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td style="width: 180px; height: 22px;"></td>
<td style="height: 22px"></td>
<td style="height: 22px"></td>
</tr>
<tr>
<td style="width: 180px"> </td>
<td> </td>
<td> </td>
</tr>
</table>
</asp:Panel>
</asp:Content>
.aspx.cs code: (code behind,including only required)
protected void gvCourses_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "delete")
{
SqlConnection con =
new SqlConnection(ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString);
DataTable dt = new DataTable();
string query =
"delete from tblCourses where course='"+e.CommandArgument.ToString()+"'";
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
int n = cmd.ExecuteNonQuery();
con.Close();
gvCourses.DataSource = dt;
gvCourses.DataBind();
ViewState["query"] = "select course from tblCourses";
bindgrid();
}
protected void bindgrid()
{
SqlConnection con =
new SqlConnection(ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString);
DataTable dt = new DataTable();
using (SqlDataAdapter sda = new SqlDataAdapter(ViewState["query"].ToString(), con))
{
sda.Fill(dt);
}
gvCourses.DataSource = dt;
gvCourses.DataBind();
}
Page looks like this(batches haven't been coded yet).
There seems to be some built-in gridview code that is created and fires when a command button is called Delete. According to this, this and this you can just change the name from Delete to anything else. Otherwise, add the empty event handler.
Btw, DataSets have CRUD functionality built-in and they can be easier to work with, but some people don't like the overhead.
I have a Gridview.aspx, Gridview.aspx.cs and GetData.cs (class)
In Gridview.aspx I have a textbox named SearchData and a button named SearchBtn
I have this in my Gridview.aspx.cs >>>
protected void SearchBtn_Click(object sender, EventArgs e){
if (!IsPostBack){
Search_Grid();
}
}
void Search_Grid(){
DataGridView.DataSource = obj.Search_Data();
DataGridView.DataBind();
}
And since it's my first time to use a class, here's what i put in GetData.cs >>>
public DataTable Search_Data(){
adap = new SqlDataAdapter("select * from MyTable " +
"where MyID = '" +
value_of_my_SearchData_textbox +
"'", con);
dt = new DataTable();
adap.Fill(dt);
return dt;
}
ASPX Code
GridView.aspx code is long, but here's what under the gridview part:
<table id="TBL_GridView" runat="server" align="center">
<tr>
<td text-align:center">*** TEST ONLY ***</td>
</tr>
<tr>
<td >
<asp:Label ID="Label1" runat="server" Text="Procedure name: "></asp:Label>
<asp:TextBox ID="SearchData" runat="server"></asp:TextBox>
<asp:Button ID="SearchBtn" runat="server" Text="Search" OnClick="SearchBtn_Click" />
</td>
</tr>
<tr >
<td >
<asp:GridView ID="DataGridView" runat="server" AutoGenerateColumns="False" ShowFooter="True"
CellPadding="4" ForeColor="#333333" GridLines="None" Height="281px" style="margin-top: 0px" Width="1000px"
OnRowCancelingEdit="DataGridView_RowCancelingEdit"
OnRowEditing="DataGridView_RowEditing" HorizontalAlign="Center" >
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:TemplateField>
<HeaderTemplate>Recipe Name</HeaderTemplate>
<ItemTemplate><asp:Label ID="recpname" runat="server" Text='<%# Bind("recpname")%>'></asp:Label></ItemTemplate>
<EditItemTemplate><asp:TextBox ID="recpname" runat="server"></asp:TextBox></EditItemTemplate>
<FooterTemplate><asp:TextBox ID="recpname" runat="server"></asp:TextBox></FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>Standard Time</HeaderTemplate>
<ItemTemplate><asp:Label ID="stdtime" runat="server" Text='<%# Bind("stdtime")%>'></asp:Label></ItemTemplate>
<EditItemTemplate><asp:TextBox ID="stdtime" runat="server"></asp:TextBox></EditItemTemplate>
<FooterTemplate><asp:TextBox ID="stdtime" runat="server"></asp:TextBox></FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>Operation</HeaderTemplate>
<ItemTemplate>
<asp:Button ID="BtnEdit" runat="server" Text="Edit" CommandName="Edit" Width="60px" />
</ItemTemplate>
<EditItemTemplate>
<asp:Button ID="BtnUpdate" runat="server" Text="Update" CommandName="Update" Width="60px" />
<asp:Button ID="BtnCancle" runat="server" Text="Cancel" CommandName="Cancel" Width="60px" />
</EditItemTemplate>
<FooterTemplate>
<asp:Button ID="BtnInsert" runat="server" Text="Insert" Width="60px" OnClick="BtnInsert_Click" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<asp:Literal ID="Literal1" runat="server"></asp:Literal>
</td>
</tr>
</table>
How should I pass the value of my textbox to my class?
I see that your text box SearchData is just an ordinary textbox outside of gridview and not in the gridview.
You can simply use:
SearchData.Text
Change the methods to pass SearchData.Text
protected void SearchBtn_Click(object sender, EventArgs e){
if (!IsPostBack){
Search_Grid(SearchData.Text);
}
}
void Search_Grid(string searchValue){
DataGridView.DataSource = obj.Search_Data(searchValue);
DataGridView.DataBind();
}
Finally use it:
public DataTable Search_Data(string searchValue){
adap = new SqlDataAdapter("select * from MyTable " +
"where MyID = '" +
searchValue +
"'", con);
dt = new DataTable();
adap.Fill(dt);
return dt;
}
However, note this code is prone to SQL Injection attack because you are adding value inline, so an attacker can add ; delete from my table to wipe your data.
You should parameterize your query.
adap = new SqlDataAdapter("select * from MyTable where MyID = #myIdValue", con);
Here is the code that works:
protected void submitForMail(object sender, EventArgs e)
{
string constr = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\TravelJoansDB.mdb;";
string cmdstr = "INSERT INTO EmailList(FirstName,LastName,EmailAddress) VALUES (#FirstName, #LastName, #EmailAddress)";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con);
TextBox tFirstName = (TextBox)FormView1.FindControl("FirstName");
TextBox tLastName = (TextBox)FormView1.FindControl("LastName");
TextBox tEmail = (TextBox)FormView1.FindControl("EmailAddress");
con.Open();
com.Parameters.AddWithValue("#FirstName", tFirstName.Text);
com.Parameters.AddWithValue("#LastName", tLastName.Text);
com.Parameters.AddWithValue("#EmailAddress", tEmail.Text);
com.ExecuteNonQuery();
con.Close();
}
Here is the code that doesn't:
protected void UpdatePic(object sender, EventArgs e)
{
string constr = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\TravelJoansDB.mdb;";
string cmdstr = "INSERT INTO BlogEntryItems(Picture) VALUES (#UpdatedPic)";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con);
TextBox uPic = (TextBox)DataList1.FindControl("BEIPictureField");
con.Open();
com.Parameters.AddWithValue("#UpdatedPic", uPic.Text);
com.ExecuteNonQuery();
con.Close();
}
Here is the code containing the Datalist1 control:
<asp:AccessDataSource ID="AccessDataSource1" runat="server"
DataFile="~/App_Data/TravelJoansDB.mdb"
SelectCommand="SELECT * FROM Table2 INNER JOIN [BlogEntryItems] ON Table2.ID=BlogEntryItems.BlogID WHERE ID=#ID" >
<SelectParameters>
<asp:QueryStringParameter Name="ID" QueryStringField="ID" />
</SelectParameters>
</asp:AccessDataSource>
<asp:DataList ID="DataList1" runat="server" DataSourceID="AccessDataSource1">
<ItemStyle />
<ItemTemplate>
<table>
<tr>
<td>
<br />
<asp:Image ID="Image1" CssClass="placePicCenter" runat="server"
BorderWidth="1px"
BorderColor="#EEEEEE"
ImageUrl='<%# "PlaceImages/" + Eval("Picture") %>' /><br />
<asp:TextBox ID="BEIPictureField" runat="server" Text='<%# Bind("Picture") %>' /><br />
<asp:Button ID="UpdatePicButton" runat="server" Text="Update" OnClick="UpdatePic" />
<br />
</td>
</tr>
<tr>
<td>
<asp:Label ID="Label4" CssClass="placeBodyStyle" runat="server" Text='<%# Eval("PicText1") %>' />
</td>
</tr>
<tr>
<td>
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
These blocks of code are for two different buttons on two different pages. The error I get when I run the second block of code is "Object reference not set to an instance of an object." Any help would be appreciated.
This line is the probable cause, it is failing to find the control BEIPictureField thus the "Object reference not set to an instance of an object." error
TextBox uPic = (TextBox)DataList1.FindControl("BEIPictureField");
EDIT 1
Try this:
TextBox uPic = (TextBox)DataList1.Items[1].FindControl("BEIPictureField");
you will have to rewrite your logic to find the control in each item not the DataList since it is the parent you will not find it there.
I save image path and image name in myqsl database. Now I want to display images from database on asp.net data-list. I have query result like this
I want to display picture with pageName. I do some thing like this on datalst.
<asp:DataList ID="dtlistImages" runat="server" RepeatColumns="3" RepeatDirection="Horizontal"
BorderColor="#336699" BorderStyle="Solid" BorderWidth="2px">
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Text='<%# Eval("pageName") %>' Font-Bold="true"
Font-Size="10pt" ForeColor="#336699" Width="100%"/>
</br>
<asp:Image ID="imgnewspaper" runat="server" ImageUrl='<%# Eval("pageNumber") %>' />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" VerticalAlign="Top" />
</asp:DataList>
Code Behind:
public DataTable getData(string query)
{
MySqlConnection conn1 = new MySqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
conn1.Open();
MySqlCommand cmd = new MySqlCommand(query, conn1);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
protected void btnshow_onclick(object sender, EventArgs e)
{
string query = "select cap_newspaper_page.pageServer,cap_newspaper_page.pagePath, pageNumber,pageName,newspaper.newspaperName,newspaper_station.newspaperStationName"+
" FROM cap_newspaper_page Inner Join cap_newspaper ON cap_newspaper_page.capnewspaperID = cap_newspaper.capnewspaperID inner join newspaper on newspaper.newspaperID=cap_newspaper.newspaperID"+
" inner join newspaper_station on newspaper_station.newspaperStationID=cap_newspaper.newspaperStationID where cap_newspaper.newspaperID="+ddlNewspaper.SelectedValue+" and cap_newspaper.newspaperStationID="+ddlNewspaperStation.SelectedValue+" and cap_newspaper_page.publishDate='"+tbDate.Text+" 00:00:00'";
dtlistImages.DataSource = getData(query);
dtlistImages.DataBind();
}
but display is like this
How I can Display images also dynamically. based on query.
what does the source code for the compiled html look like? clearly the image paths must be invalid. if you check what the asp has written does this not give a strong clue as to what is wrong?
You only have pageNumber and not pagePath in your Eval
<asp:Image ID="imgnewspaper" runat="server" ImageUrl='<%# Eval("pagePath") %>' />
or
you are missing the images in your project folder printImages locally, if your are running it locally, and if you are running it on live server then also check that folder for images.
Suggestion I have achieved the same thing in the following way:
<asp:ListView ID="ImagesList" runat="server" DataKeyNames="ID" GroupItemCount="4" OnPagePropertiesChanging="ImagesList_PagePropertiesChanging">
<EmptyDataTemplate>
No Images found.
</EmptyDataTemplate>
<ItemTemplate>
<asp:ImageButton ID="MyPicture" runat="server" OnClick="MyPicture_Click" CommandArgument='<%# Eval("ID") %>' AlternateText='<%# Eval("Name") %>' ImageUrl='<%# Eval("ImagePath") %>' Autopostback="true"Width="155" Height="80" />
</ItemTemplate>
</asp:ListView>
I have Image in ItemTemplate that will be changing according to Username (ie lblPostedBy.Text). I have written code in onItemCommand of repeater control in C# Asp.net 4.0. But not working. Will you please help me.
protected void myrepeater_ItemCommand1(object source, RepeaterCommandEventArgs e)
{
// Actually lblPostedBy is a linkbutton and lblPostedBy.Text is 'username of the commenter'.
LinkButton lblPostedBy = (LinkButton)e.Item.FindControl("lblPostedBy");
con.Open();
cmd.CommandText = "select image from " + lblPostedBy.Text + " where id=1";
// 'image' column in table stores path of image like '~/image/image1.jpg'
cmd.Connection = con;
string imageurl = (string)cmd.ExecuteScalar();
con.Close();
Image Image1 = (Image)e.Item.FindControl("Image1");
Image1.ImageUrl = imageurl;
}
and
<asp:Repeater ID="myrepeater" runat="server"
onitemcommand="myrepeater_ItemCommand1">
<HeaderTemplate>
<table width="100%" style="font: 8pt verdana">
<tr style="background-color:#3C78C3">
<th>NEWS FEED</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td valign="top">
<asp:Image ID="Image1" runat="server" Height="50px" Width="50px" />
<asp:LinkButton ID="lblPostedBy" runat="server" onclick="lblPostedBy_Click" Text='<%#DataBinder.Eval(Container,"DataItem.postedby") %>' />   says : <br />
<asp:TextBox id="txtPost" runat="server" Width="100%" textmode="multiline" text='<%#DataBinder.Eval(Container,"DataItem.scraps")%>' ReadOnly="True" BackColor="#EFF3FB" BorderStyle="None"></asp:TextBox>
<%#DataBinder.Eval(Container,"DataItem.scraptime") %>
<br />
<asp:TextBox ID="TextBox2" runat="server" Visible="False" Width="80%"></asp:TextBox>
<asp:Button ID="btnDoneComment" runat="server" Text="Done" Visible="False" onclick="btnDoneComment_Click"/>
<br />
<hr style="border:dashed 1px blue" />
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
Thanks in Advance,
Regards,
Nikhil
Instead of "cmd.CommandText = "select image from " + lblPostedBy.Text;"
Shouldn't it be
cmd.CommandText = "select image from TableName where pby = '" + lblPostedBy.Text + "'";
Better yet, add a parameter
cmd.CommandText = "select image from tablename where pby = #pby"
cmd.Parameters.Add(new SalParameter("#pby", lblPostedBy.Text);