How can I display images in GridView from a folder in my project?
Iv'e tried to create an image/imageField dynamically, but it didn't work- I don't know how to connect the images to the imageField in my GridView, and that's my main problem.
How can I do it?
Here's my GridView:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
Height="271px" onselectedindexchanged="GridView1_SelectedIndexChanged"
style="font-family: Arial, Helvetica, sans-serif" Width="452px">
<Columns>
<asp:BoundField DataField="messageSubject" HeaderText="subject" />
<asp:BoundField DataField="messageContent" HeaderText="content" />
<asp:BoundField DataField="wasReadOrNot" HeaderText="was read" />
<asp:ImageField HeaderText="image">
</asp:ImageField>
</Columns>
</asp:GridView>
(In addition, it's okay to use imageField at all?)
And here's my Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
Page.MaintainScrollPositionOnPostBack = true;
if (!IsPostBack)
{
WebServiceDBMessages.WebServiceDBMessagesSoapClient dbm = new WebServiceDBMessages.WebServiceDBMessagesSoapClient();
DataTable dt = dbm.ReturnAllMessagesForTeacher(Session["teacher"].ToString()).Tables[0];
for (int i = 0; i < GridView1.Rows.Count; i++)
{
if (GridView1.Rows[i].Cells[3].Text == "not read")
{
//here i want to display image whose url is: "/images/notRead.png"
}
else
{
//here i want to display image whose url is: "/images/read.png"
}
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
Thanks(:
The image url is not in the dataset so can change your GridView definition to
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
Height="271px" onselectedindexchanged="GridView1_SelectedIndexChanged"
style="font-family: Arial, Helvetica, sans-serif" Width="452px" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="messageSubject" HeaderText="subject" />
<asp:BoundField DataField="messageContent" HeaderText="content" />
<asp:BoundField DataField="wasReadOrNot" HeaderText="was read" />
<asp:TemplateField HeaderText="image">
<ItemTemplate>
<asp:Image runat="server" ID="img" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Change your page load to
protected void Page_Load(object sender, EventArgs e)
{
Page.MaintainScrollPositionOnPostBack = true;
if (!IsPostBack)
{
WebServiceDBMessages.WebServiceDBMessagesSoapClient dbm = new WebServiceDBMessages.WebServiceDBMessagesSoapClient();
DataTable dt = dbm.ReturnAllMessagesForTeacher(Session["teacher"].ToString()).Tables[0];
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
Add following
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var image = e.Row.FindControl("img") as Image;
image.ImageUrl = e.Row.Cells[3].Text == "not read" ? "/images/notRead.png" : "/images/read.png";
}
}
This should accomplish what you are trying to do.
Related
I am having asp.net gridview wherein I am showing several record with select option.
But as per my requirement I only want 1st row on grid to have select option.
below is my aspx page code:
<asp:GridView ID="id" runat="server" AutoGenerateColumns="False" CellPadding="3"
ShowHeaderWhenEmpty="true" AutoGenerateSelectButton="True" PageSize="5" CssClass="mGridSmall"
GridLines="None" PagerStyle-CssClass="pgr" AlternatingRowStyle-CssClass="alt"
OnPageIndexChanging="id_PageIndexChanging" OnRowDataBound="id_RowDataBound"
OnSelectedIndexChanged="id_SelectedIndexChanged">
<AlternatingRowStyle CssClass="alt" />
<Columns>
<asp:BoundField DataField="Col1" Visible="false" />
<asp:BoundField DataField="Col2" HeaderText="Col2" SortExpression="Col2"
Visible="true" />
<asp:BoundField DataField="Col3" HeaderText="Col3" SortExpression="Col3"
Visible="true" />
<asp:BoundField DataField="Col4" HeaderText="Col4" SortExpression="Col4"></asp:BoundField>
<asp:BoundField DataField="Col5" HeaderText="Col5" SortExpression="Col5"></asp:BoundField>
<asp:BoundField DataField="Col6" HeaderText="Col6" SortExpression="Col6"></asp:BoundField>
<asp:BoundField DataField="Col7" Visible="false"></asp:BoundField>
</Columns>
<PagerStyle CssClass="pgr" />
<SelectedRowStyle BackColor="#fcb814" />
</asp:GridView>
and here is my .cs file code for row binding:
protected void id_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView drv = (DataRowView)e.Row.DataItem;
//sorting
e.Row.Cells[1].Text = Convert.ToString(drv.Row["Col1"]);
e.Row.Cells[2].Text = Convert.ToString(drv.Row["Col2"]);
//e.Row.Cells[3].Text = Convert.ToString(drv.Row["Col3"]);
e.Row.Cells[3].Text = Convert.ToString(drv.Row["Col3"]);
e.Row.Cells[4].Text = Convert.ToString(drv.Row["Col4"]);
e.Row.Cells[5].Text = Convert.ToString(drv.Row["Col5"]);
e.Row.Cells[6].Text = Convert.ToString(drv.Row["Col6"]);
e.Row.Cells[7].Text = Convert.ToString(drv.Row["Col7"]);
}
}
catch (Exception ex)
{
clsErrorHandler.LogError(ex);
}
}
You can do this in the RowDataBound event. Check the Row Index and hide the Control in all the Cells but the first.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.DataItemIndex > 0)
{
LinkButton lb = e.Row.Cells[0].Controls[0] as LinkButton;
lb.Visible = false;
}
}
}
Here is my aspx.cs page code. Every time when I run the code the only answer I get is: Column name doesn't exist.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
CssClass="table table-striped table-bordered table-hover" >
<Columns>
<asp:BoundField DataField="TutorialId" HeaderText="Tutorial Id"/>
<asp:BoundField DataField="TutorialTitle" HeaderText="TutorialTitle"/>
<asp:BoundField DataField="CatId" HeaderText="Category Id" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkview" runat="server" OnClick="lnk_OnClick"
CommandArgument='<%#Eval("TutorialId") %>'>View</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And here is my aspx code. Here I have used click event on the link
button which is getting the ID number:
protected void lnk_OnClick(object sender, EventArgs e)
{
int TutorialId = Convert.ToInt32((sender as LinkButton).CommandArgument);
GetTutorialById();
}
private void GetTutorialById()
{
OnlineSubjects onlinesubject = new OnlineSubjects();
DataTable dTable = onlinesubject.GetTutorialById();
txtTutId.Text = dTable.Rows[0]["TutorialId"].ToString();
txtTitle.Text = dTable.Rows[0]["TutorialTitle"].ToString();
txtAddTutorial.Text = dTable.Rows[0]["TutorialDesc"].ToString();
}
public DataTable GetTutorialById()
{
SqlParameter[] parameters = new SqlParameter[1];
parameters[0] = DataLayer.DataAccess.AddParameter(
"#TutorialId", TutorialId, System.Data.SqlDbType.Int, 100);
DataTable dTable = DataLayer.DataAccess.ExecuteDTByProcedure(
"spTutorialViewById", parameters);
return dTable;
}
I can't seem to make data from my gridview pass to textboxes outside of my gridview on row selection. The event seems to be firing, but the textboxes are always filled with & nbsp;. I can't figure out why this is happening since none of the cells in the gridview are blank. I have been researching this problem for a few days, on this site and other sites, with no luck. Here is the piece of my aspx.cs:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
txtBLName.Text = GridView1.Rows[GridView1.SelectedIndex].Cells[1].Text;
}
Here is my gridview code:
<asp:GridView ID="GridView1"
runat="server"
AutoGenerateColumns="False"
onselectedindexchanged="GridView1_SelectedIndexChanged" >
<Columns>
<asp:CommandField ShowSelectButton="true" SelectText="Edit" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" SortExpression="LastName"/>
</Columns>
</asp:GridView>
Can someone please help? Thanks!
It's Working
ASP CODE
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:GridView ID="GridView2"
runat="server"
AutoGenerateColumns="False"
onselectedindexchanged="GridView2_SelectedIndexChanged" >
<Columns>
<asp:CommandField ShowSelectButton="true" SelectText="Edit" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" SortExpression="LastName"/>
</Columns>
C# CODE
protected void Page_Load(object sender, EventArgs e)
{
DataTable oDT = new DataTable();
oDT.Columns.Add("edit",typeof(string));
oDT.Columns.Add("LastName", typeof(string));
oDT.Rows.Add("ad", "1212121");
oDT.Rows.Add("aad", "1asdasd212121");
GridView2.DataSource = oDT;
GridView2.DataBind();
}
protected void GridView2_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView2.SelectedRow;
TextBox1.Text = row.Cells[1].Text;
}
RESULT
i have a datset that i save into viewstate and i want to paging on that dataset.
Code for bind gridview
DataSet _ds = _fOrderInvoice.ExecuteDataSet();
ViewState["FIOrders"] = _ds.Tables[0];
grdInvoiced.DataSource = _ds; // bind the gridview
Now i want paging on the gridview. So how can i do that from the dataset that i have save into my ViewState["FIOrders"]. My gridview is below
<asp:GridView ID="grdInvoiced" runat="server" Width="100%" ViewStateMode="Enabled" DefaultSortColumnName="OrderNo" OnSelectedIndexChanged="GridInvoice_SelectedIndexChanged" AutoGenerateColumns="False" OnSorting="invoice_sorting" OnRowDataBound="grdInvoice_Rowdatabount" ShowFooter="true" PageSize="20" AllowPaging="True" AllowSorting="True" DataKeyNames="OrderNo" ExcelExportFileName="Export_AccountTerms.xls"
ShowHeaderWhenEmpty="true" OnPageIndexChanging="grdInvoiced_PageIndexChanging">
<Columns>
<asp:CommandField ShowSelectButton="True" SelectText="View" />
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="rbtnSelect" GroupName="a" runat="server" />
<asp:Literal ID="ltOrder" runat="server" Text='<%# Eval("OrderNo")%>' Visible="false"></asp:Literal>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left" Width="50px" />
</asp:TemplateField>
</Columns>
</asp:GridView>
PageIndexChanging event
protected void grdInvoiced_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grdInvoiced.PageIndex = e.NewPageIndex+1;
if (ViewState["FOrders"] != null)
{
DataTable ds = (DataTable)ViewState["FIOrders"];
grdInvoiced.PageIndex = e.NewPageIndex + 1;
// Collection<FinalizedOrderInvoiceRows> _rows = ViewState["FIOrders"] as Collection<FinalizedOrderInvoiceRows>;
grdInvoiced.DataSource = ds;
grdInvoiced.DataBind();
}
}
Convert Your ViewState into DataSet and Bind it to GridView
protected void grdInvoiced_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grdInvoiced.PageIndex = e.NewPageIndex;
if (ViewState["FOrders"] != null)
{
DataSet ds =(DataSet) ViewState["FIOrders"] ;
grdInvoiced.DataSource = ds;
grdInvoiced.DataBind();
}
}
So I am working on a basketball website. There is a gridview full of teams and what I would like is when you click on a team name, it links you to a new page that has info about the team. What I tried so far only links every team to the same details page.
Here is my gridview code:
<asp:GridView ID="GridView1" runat="server" AllowSorting="True"
AutoGenerateColumns="False" CellPadding="4" DataKeyNames="Team"
DataSourceID="SqlDataSource1" ForeColor="#333333" GridLines="None"
Height="340px" Width="776px">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:HyperLinkField DataTextField="Team" DataNavigateUrlFields="Rank" DataNavigateUrlFormatString="~/MemberPages/Details.aspx?Rank={0}"
HeaderText="Team" SortExpression="Team" ItemStyle-Width = "150" >
<ItemStyle Width="150px"></ItemStyle>
</asp:HyperLinkField>
<asp:BoundField DataField="Rank" HeaderText="Rank" SortExpression="Rank" />
<asp:BoundField DataField="PointsPerGame" HeaderText="PointsPerGame"
SortExpression="PointsPerGame" />
<asp:BoundField DataField="OpponentPointsPerGame"
HeaderText="OpponentPointsPerGame" SortExpression="OpponentPointsPerGame" />
<asp:BoundField DataField="TopPlayer" HeaderText="TopPlayer"
SortExpression="TopPlayer" />
</Columns>
</asp:GridView>
And here is what I tried in the cs file to databind them to a specific link:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[5] { new DataColumn("Team"),new DataColumn("Ranking"), new DataColumn("PointsPerGame"),
new DataColumn("OpponentPointsPerGame"), new DataColumn("TopPlayer")});
GridView1.DataBind();
}
}
For that kind of show/hide logic on specific row, you will need to use GridView.RowDataBound event.
Use a TemplateField instead of BoundField.
Place HyperLink control inside.
Then retrieve the HyperLink control inside RowDataBound event.
Example Code
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink runat="server" ID="MyHyperLink" Text="My Text" />
</ItemTemplate>
</asp:TemplateField>
protected void GridView1_RowDataBound(
Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
var myHyperLink = e.Row.FindControl("MyHyperLink") as HyperLink;
if(SOME_LOGIC)
{
myHyperLink.Visible = false;
}
}
}