Display Images from Mysql database in Datalist - c#

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>

Related

asp.net c# need to redirect to another page with value

I have a page that has a gridview control that lists item info and has options to view the items in detail, and also to open a page to edit the item and save the result as a "clone". This works fine, but now I want to add a button to the detail view page to clone the record without having to return to the list page and select the clone item.
working gridview control on list page:
<asp:GridView ID="GridView1" runat="server" Caption="Submitted Questions" AllowSorting="True"
CaptionAlign="Left" EmptyDataText="You have not submitted any Questions." PageSize="5"
AutoGenerateColumns="false" AlternatingRowStyle-BackColor="#cccccc">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="QuestionID" runat="server" Text='<%# Eval("QuestionID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="KeyObjective" HeaderText="Key Objective" ItemStyle-Width="150" />
<asp:BoundField DataField="SubmitDate" HeaderText="Submitted Date" ItemStyle-Width="50" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="Details" runat="server" Text="View Details" PostBackUrl='<%#"~/Submit/Detail.aspx?Id=" + Eval("QuestionID") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="Clone" runat="server" Text="Create Clone" PostBackUrl='<%# "~/Submit/Clone.aspx?Id=" + Eval("QuestionID") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Current attempt at the button control:
dropped the javascript below and moved to code behind:
Button:
<asp:Button ID="CloneButton" runat="server" Text="Clone This Question" OnClick="CloneButton_Click" />
Code behind:
protected void CloneButton_Click(object sender, EventArgs e)
{
Response.Redirect("~/Submit/Clone.aspx?Id=" + txt_QuestionID);
}
Now it looks like the app is trying to open the clone page but is having issue with interpreting the value passed for Id?
Error occuring here on the clone page: Error received is "Input string was not in a correct format."
using (Conn)
{
SqlCommand command = new SqlCommand("sp_CloneSElect", Conn);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#QuestionID", SqlDbType.BigInt));
command.Parameters["#QuestionID"].Value = Convert.ToInt32(Request["Id"]);
Conn.Open();
SqlDataReader reader = command.ExecuteReader();
Ignore below here as no longer used (saved for reference to notes already submitted).
Javascript:
<script type="text/javascript">
function redirect(QuestionID) { location.href = '~/Submit/Clone.aspx?Id=' + QuestionID; }
</script>
Button:
<asp:Button ID="CloneButton" runat="server" OnClientClick='redirect(<%#Eval("QuestionID") %>; return false' Text="Clone Question" />
Button is not inside of a table, grid, or other control set.
I see a couple of issues.
OnClientClick='redirect(<%#Eval("QuestionID") %>; return false'
has a parentheses missing after >
OnClientClick='redirect(<%#Eval("QuestionID") %>); return false'
Also
location.href = '~/Submit/Clone.aspx?Id=' + QuestionID;
is inside an ordinary html script tag so ~ won't be replaced by server
If <%#Eval("QuestionID") %> returns a string like QUEST3123234 you'd need to add quotation marks. If it's a number, then they are not needed.
Figured it out.
Button control:
<asp:Button ID="CloneButton" runat="server" Text="Clone This Question" OnClick="CloneButton_Click" />
Code Behind:
protected void CloneButton_Click(object sender, EventArgs e)
{
Response.Redirect("~/Submit/Clone.aspx?Id=" + txt_QuestionID.Text);
}
Thanks to all for assisting to jar a newbies brain cells.

Label Text not saving in database

Hi I am Using Gridview in which i have one column of checkbox and one of labels on checking the text of label is changing but when i am inserting it into database, it is taking default value of label.
Html
<asp:GridView ID="grdData" runat="server" style="Text-align:center;">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" onclick="changeTextValue(this); ChildCheckBox(this)"/>
</ItemTemplate>
<HeaderTemplate>
<asp:CheckBox ID="CheckBox2" runat="server" OnClick="CheckAllEmp(this)"/>
</HeaderTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<asp:Label ID="Status_Header" runat="server" Text="Status"/>
<HeaderTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" EnableViewState="true" ClientIDMode="Static">0</asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
This is my codebehind code:
foreach (GridViewRow g1 in grdData.Rows)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Real_Attendance"].ConnectionString);
using (SqlCommand cmd = new SqlCommand("Insert into Attendanc (Stu_id,Status,time,Date,Sub_id) values (#Stu_id, #Status, #Time, #Date, #Sub_id)", con))
{
cmd.Parameters.AddWithValue("#Stu_id", g1.Cells[3].Text);
cmd.Parameters.AddWithValue("#Status", ((Label)(g1.FindControl("Label1"))).Text);
cmd.Parameters.AddWithValue("#Time", Session["Time_Value"].ToString());
cmd.Parameters.AddWithValue("#Date", date);
cmd.Parameters.AddWithValue("#Sub_id", Session["Sub_id"].ToString());
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
You can use a HiddenField to keep the same value with Label1.
Gridview
<ItemTemplate>
<asp:Label ID="Label1" runat="server" EnableViewState="true" ClientIDMode="Static">0</asp:Label>
<asp:HiddenField ID="HiddenField1" Value="0" runat="server" />
</ItemTemplate>
Javascript
changeTextValue(obj)
{
//in the end
var Label1Value=1;//your Label1 value
$(obj).parents("tr").find("input[type=hidden]").val(Label1Value);
}
C#
cmd.Parameters.AddWithValue("#Status", ((HiddenField)(g1.FindControl("HiddenField1"))).Value);

C# - Set null to empty string on SQL SELECT?

I would like to replace any null values for a field with an empty string when I select items from the database. Currently, what I have works fine in SQL Management Studio, but when I place it in my C# code's SELECT statement, the column I want to be empty if the value is null does not display. I do not see any error messages displaying.
I am still learning SQL, so I am not sure how to fix the query so that all 3 columns are displayed in the browser in the gridview regardless of whether the ThumbnailUrl field is null or not.
Any help is appreciated! Thanks!
Gridview code in the designer:
<cb:SortedGridView ID="SearchResultsGrid" runat="server" AutoGenerateColumns="False" DataKeyNames="ProductId" GridLines="None" SkinID="PagedList" Width="100%" Visible="false" >
<Columns>
<asp:TemplateField HeaderText="Thumbnail">
<ItemStyle HorizontalAlign="Center" />
<ItemTemplate>
<asp:HyperLink ID="NodeImageLink" runat="server" NavigateUrl='<%# UrlGenerator.GetBrowseUrl((int)Eval("ProductId"), CatalogNodeType.Product, (string)Eval("Name")) %>'> <asp:Image ID="NodeImage" runat="server" ImageUrl='<%# Eval("ThumbnailUrl") %>' Visible='<%# !string.IsNullOrEmpty((string)Eval("ThumbnailUrl")) %>' AlternateText='<%# Eval("Name") %>' /> </asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="SKU" SortExpression="Sku">
<HeaderStyle HorizontalAlign="Left" />
<ItemTemplate>
<asp:HyperLink ID="ProductSku" runat="server" Text='<%#Eval("Sku")%>' SkinID="FieldHeader" /><br />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Item" SortExpression="Name" >
<HeaderStyle HorizontalAlign="Left" />
<ItemTemplate>
<asp:HyperLink ID="ProductName" runat="server" Text='<%#Eval("Name")%>' SkinID="FieldHeader" /><br />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Assigned">
<ItemStyle Width="50px" HorizontalAlign="Center" />
<ItemTemplate>
<asp:ImageButton ID="AttachButton" runat="server" CommandArgument='<%#Container.DataItemIndex%>' AlternateText="Add" ToolTip="Add" SkinID="AddIcon" OnClientClick="this.visible=false" OnClick="AttachButton_Click" Visible='<%#!IsProductLinked((int)Eval("ProductId"))%>' />
<asp:ImageButton ID="RemoveButton" runat="server" CommandArgument='<%#Container.DataItemIndex%>' AlternateText="Remove" ToolTip="Remove" SkinID="DeleteIcon" OnClientClick="return confirm('Are you sure you want to remove this item from this option?')" OnClick="RemoveButton_Click" Visible='<%#IsProductLinked((int)Eval("ProductId"))%>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
There are no products that match the search text.
</EmptyDataTemplate>
</cb:SortedGridView>
This is the code:
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
if (SearchName.Text != "")
{
try
{
cmd.CommandText = "SELECT ProductID, ISNULL(ThumbnailUrl, '') AS ThumbnailUrl, Name, Sku FROM ac_Products WHERE Name LIKE '%' + #Name + '%'";
cmd.Parameters.AddWithValue("#Name", SearchName.Text);
cn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
SearchResultsGrid.DataSource = dt;
SearchResultsGrid.DataBind();
SearchResultsGrid.Columns[0].Visible = ShowImages.Checked;
}
catch (Exception x)
{
Logger.Error(ErrLoc + " PopulateSearchGrid(): ", x);
errorLbl2.Text = "PopulateSearchGrid() Name Search Error: " + x.Message.ToString();
}
finally
{
cn.Close();
}
}
I'm not quite sure what you mean by "does not display". An empty value actually doesn't display anything. I doubt that this is an SQL problem, as your statement looks fine (apart from what I write at the bottom about parameterizing your query). I guess it is a binding problem. You can try one of the following:
Instead of ISNULL(ThumbnailUrl, '') AS ThumbnailUrl try ISNULL(ThumbnailUrl, '-') AS ThumbnailUrl and check whether you see the - now.
If this is a Windows Forms application you can try to add the columns to the grid in the designer and set the AutoGenerateColumns property to false. Please note that you can set this property only in code, not in the designer.
If this is WPF, check whether you actually have a column definition for the required field. Maybe you have a typo on the binding configuration? The binding names are case sensitive! If you return ThumbnailUrl from the database, the binding ThumbNailUrl will not work.
As a side note: Thumbs up for trying to use parameterized queries, but it don't think you're doing it right in this case. It should read like this:
cmd.CommandText = "SELECT ProductID, ISNULL(ThumbnailUrl, '') AS ThumbnailUrl, Name, Sku FROM ac_Products WHERE Name LIKE #Name";
cmd.Parameters.AddWithValue("#Name", String.Format("%{0}%", SearchName.Text));

Update Selected Row in Gridview

I want to update only selected row from my grid view when i press linked button but it is not working on my end .
Here is my Design Page
<asp:GridView ID="grdCompanyUsers" runat="server"
DataKeyNames="id_company_user,nm_company_username"
AutoGenerateColumns="false" GridLines="None" CssClass="grid" AlternatingRowStyle-
BackColor="#DDE0EF" OnRowDataBound="grdCompanyUsers_DataBound">
<Columns>
<asp:TemplateField>
<EditItemTemplate>
<asp:ImageButton ID="imgbtnCancel" runat="server" CommandName="Cancel" ImageUrl="~/Images
/Cancel.jpg" ToolTip="Cancel" Height="20px" Width="20px" />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="CompUserID" runat="server" Width="15"
Text='<%#Eval("id_company_user")%>'> </asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="companyusername" runat="server" Width="51"
Text='<%#Eval("nm_company_username")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="compName" runat="server" Width="56" Text='<%#Eval("nm_company_name")%>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="compDesc" runat="server" Width="129" Text='<%#Eval("nm_company_desc")%>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="compEmail" runat="server" Width="103px"
Text='<%#Eval("nm_company_email_address")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="compAddress" runat="server" Width="153px"
Text='<%#Eval("nm_company_address")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkBoxStatus" runat="server" Width="15px" Enabled="false"
Text='<%#Eval("ind_active")%>'>
</asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="btnEdit" runat="server" Font-Underline="false"
CommandArgument='<%#Eval ("id_company_user")%>'
OnClick="btnEdit_Click">Edit</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" ID="lnkDeny" Font-Underline="false" CommandName="Deny"
CommandArgument='<%# Eval("id_company_user") %>'
OnClick="btnDeny_Click">Deny</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Here is my code behind the aspx page
protected void btnEdit_Click(object sender, EventArgs e)
{
LinkButton btn = (LinkButton)sender;
GridViewRow row = (GridViewRow)btn.NamingContainer;
int i = Convert.ToInt32(row.RowIndex);
_connString = ConfigurationManager.AppSettings["connString"];
using (SqlConnection conn = new SqlConnection(_connString))
{
conn.Open();
SqlCommand cmd = new SqlCommand("update ref_registration_company_user
set ind_active=1 where id_company_user=id_company_user", conn);
cmd.ExecuteNonQuery();
conn.Close();
}
}
Here is Design View :
I just want that only selected row should be affected in database.
I will be thank full for help.
you need to set the id_company_user value in your sql statement. use parameters as below.
SqlCommand cmd = new SqlCommand("update ref_registration_company_user set ind_active=1 where id_company_user=#id_company_user", conn);
cmd.Parameters.AddWithValue("#id_company_user", id);
you need to get current row id_company_user value check below SO question and answer, you can use
OnRowCommand of GridView and CommandArgument property
GridView: Get datakey of the row on button click
<asp:GridView ID="grdCompanyUsers" runat="server" DataKeyNames="id_company_user,nm_company_username" AutoGenerateColumns="false" GridLines="None" CssClass="grid" AlternatingRowStyle-BackColor="#DDE0EF" OnRowDataBound="grdCompanyUsers_DataBound"
OnRowCommand="myGridView_RowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="btnEdit" runat="server" Font-Underline="false" CommandArgument='<%#Eval ("id_company_user")%>' CommandName="Edit">Edit</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
code-behind:
protected void myGridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
var id= int.Parse(e.CommandArgument);
_connString = ConfigurationManager.AppSettings["connString"];
using (SqlConnection conn = new SqlConnection(_connString))
{
conn.Open();
using(SqlCommand cmd = new SqlCommand("update ref_registration_company_user set ind_active=1 where id_company_user=id_company_user", conn))
{
cmd.Parameters.AddWithValue("#id_company_user", id);
cmd.ExecuteNonQuery();
}
}
}
Can you please check once your update query where clause,
Check the sqlDataSource control for this problem, you can add the select and update command for populate and update rows your GridView on there.
Maybe this example could be you useful
http://asp-net-example.blogspot.mx/2008/12/aspnet-gridview-and-sqldatasource.html

add hyperlink to a gridview

I am creating a webpage using C# and asp.net
I have a simple sqlite database.
I have a gridview where i am displaying just simple 2 Book categories.
The two categories are
Fiction
technical
I would like to assign a link to those categories so the user can be directed to a new page.
Here is a snapshot of the data being displayed in the gridview..
where i want to add a link to Fiction and technical to redirect to a new page.
This is my dataset and gridview.
DataSet dsgrid;
dsgrid = (DataSet)Cache["GridViewDataSet"];
if (dsgrid == null)
{
dsgrid = GetDataSet(); //call function
Cache["GridViewDataSet"] = dsgrid;
}
else
{
}
//bind our cache data to a datasource
GridView1.DataSource = dsgrid.Tables[0];
GridView1.DataBind();
}
catch (Exception ex)
{
this.lblError.Text = ex.Message;
}
}
private DataSet GetDataSet()
{
String connectionString = "Data Source=" + Server.MapPath(#"~\App_Data\bookDB.db");
String selectCommand = "Select * from Category";
SQLiteDataAdapter dataAdapter = new SQLiteDataAdapter(selectCommand, connectionString);
DataSet ds = new DataSet();
dataAdapter.Fill(ds);
//GridView1.DataSource = ds;
// GridView1.DataBind();
return ds;
}
Thank you
Here are a few options, which one you choose will depend on the amount of flexibility you need.
Built in button column:
<asp:GridView >
<Columns>
<asp:ButtonColumn DataField="some_field" Visible="false" ButtonType="linkButton" />
</Columns>
/<asp:GridView >
Column template: (This will give you the most flexibility.)
<asp:GridView>
<Columns>
<asp:TemplateField HeaderText="Its a link!">
<ItemTemplate>
<asp:LinkButton ID="SomeName" runat="server" Text=''>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Enjoy!
this is the markup code, you have to add a hyperlink to the gridview control inside the IntemTempalte collection and add a binding expression to the text property of the contained controls
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="128px">
<Columns>
<asp:TemplateField HeaderText="Code">
<ItemTemplate>
<asp:Label ID="lblCodigo" runat="server" Text='<%#Eval("columnNae")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:HyperLink ID="link" runat="server" Text='<%#Eval("columnNae") %>' NavigateUrl="http://nudierweb.somee.com"></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
You need to use HyperLinc control
<asp:HyperLink id="hyperlink1" NavigateUrl="http://www.yournavigateurl.com"
Text="Your Hyperlink text" runat="server"/>
Try like this
<asp:HyperLinkField DataTextField="Value of column you want to make as HYPERLINK" HeaderText="COLUMN NAME" runat="server" DataNavigateUrlFields="Value you want to pass to other page(fname)" DataNavigateUrlFormatString="~/demo.aspx(another page name)?fname**strong text**={0}"/>
eg:
<asp:HyperLinkField DataTextField="stid" HeaderText="stid" Target="_self" runat="server" DataNavigateUrlFields="fname" DataNavigateUrlFormatString="~/demo.aspx?fname={0}"/>

Categories

Resources