Displaying a default image in gridview - asp.net

How to display a defualt profile image in gridview if user didn't provided any image.
if (fileUpload.PostedFile == null)
{
lblStatus.Text = "No file specified.";
return;
}
else
{
{

One approach might be to check each row during RowDataBound event to see image exists or not. If it is empty, you can assign a default image url.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
Image image= (Image)e.Row.FindControl("ImageForPerson");
if (image != null && image.ImageIrl == "")
{
image.ImageUrl = // default image url goes here
}
}
}
Do not forget to add RowDataBound event to your GridView definition.
<asp:GridView ID="GridView1" OnRowDataBound="GridView1_RowDataBound" />
Or If you do not want to use RowDataBound event. At Page_Load you can manually go through each Row of GridView and check ImageUrl one by one.
protected void Page_Load(object sender, EventArgs e)
{
foreach(GridViewRow gvr in GridView1.Rows)
{
Image image = (Image)gvr.FindControl("ImageForPerson");
if (image != null && image.ImageIrl == "")
{
image.ImageUrl = // default image url goes here
}
}
}

This could also be done in a single line in the aspx itself. By using a ternary operator.
<asp:Image ID="Image1" runat="server" ImageUrl='<%# !string.IsNullOrEmpty(Eval("userImage").ToString()) ? "/images/" + Eval("userImage") : "/images/noimage.jpg" %>' />

Related

How to force RadGrid to postback when inner grid expand

I have a hierarchical RadGrid and I wrote the following code that works when I select a row because I set EnablePostBackOnRowClick="true" but I want to when I expand the subgrid, it fill but now I had to select the row to bind detail grid.
protected void RadGrid1_DetailTableDataBind(object source, Telerik.Web.UI.GridDetailTableDataBindEventArgs e)
{
//e.DetailTableView.Items[e.DetailTableView.ParentItem.ItemIndex]["ID_"].Text
try
{
if (x != "0")
{
x = RadGrid1.Items[RadGrid1.SelectedIndexes[0]]["ID_"].Text.ToString();
}
GridDataItem dataItem = (GridDataItem)e.DetailTableView.ParentItem;
// Label2.Text = e.DetailTableView.Items[0]["ControlName"].Text.ToString();
e.DetailTableView.DataSource = GetDataTable("[Prg].[S_ControlList_Select]", x);
}
}
In order to have your page fire a postback when you expand the subgrid, just set the following:
In your RadGrid's definition, add the OnItemCommand setting and the ClientSettings section:
<telerik:RadGrid ID="RadGrid1" OnItemCommand="RadGrid1_ItemCommand"
<ClientSettings AllowExpandCollapse="true">
In the code behind, handle the postback:
protected void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e)
{
switch (e.CommandName)
{
case "ExpandCollapse":
// Do something...
break;
}
}

Wrong linkbutton command argument after sorting gridview

In an asp:TemplateField column of a GridView, I have a LinkButton that passes a command argument to a function that deletes the row when it is clicked. However, after the GridView is sorted, the LinkButton passes the wrong argument. Also, the GridView loses the sort order.
What am I doing wrong?
Here is my code:
<!---master page---->
<asp:GridView runat="server" ID="companies_grid" AllowSorting="true"
AutoGenerateColumns="false" OnSorting="companies_grid_OnSorting"
OnRowDataBound="companies_grid_OnRowDataBound" >
<Columns>
<%--Company Name--%>
<asp:TemplateField HeaderText="Company Name" SortExpression="Name">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server"
OnClick="removeCompany_click" />
<a href='<%#Eval("URL")%>'><%#Eval("Name")%></a>
</ItemTemplate>
</asp:TemplateField>
//more columns
<!---code behind---->
protected void Page_Load(object sender, EventArgs e)
{
companies = GetCompanyData();
companies_grid.DataSource = companies;
companies_grid.DataBind();
}
protected void companies_grid_OnSorting(object sender, GridViewSortEventArgs e)
{
//sort is made up of column to sort by + direction
companies.DefaultView.Sort = e.SortExpression.ToString() + " " + GetSortDirection(e.SortExpression, "companiesExpression", "companiesDirection");
companies_grid.DataSource = companies;
companies_grid.DataBind();
}
private string GetSortDirection(string column, string expressionViewState, string directionViewState)
{
// By default, set the sort direction to ascending.
string sortDirection = "ASC";
// Retrieve the last column that was sorted.
string sortExpression = ViewState[expressionViewState] as string;
if (sortExpression != null)
{
// Check if the same column is being sorted.
// Otherwise, the default value can be returned.
if (sortExpression == column)
{
string lastDirection = ViewState[directionViewState] as string;
if ((lastDirection != null) && (lastDirection == "ASC"))
{
sortDirection = "DESC";
}
}
}
// Save new values in ViewState.
ViewState[directionViewState] = sortDirection;
ViewState[expressionViewState] = column;
return sortDirection;
}
protected void companies_grid_OnRowDataBound(Object Sender, GridViewRowEventArgs e)
{
GridViewRow currRow = e.Row;
if (currRow.RowType == DataControlRowType.DataRow)
{
LinkButton deleteCompButton = (LinkButton)e.Row.FindControl("LinkButton1") as LinkButton;
deleteCompButton.CommandArgument = ((DataRowView)e.Row.DataItem)["Company_ID"].ToString();
deleteCompButton.Text = ((DataRowView)e.Row.DataItem)["Company_ID"].ToString();
}
}
protected void removeCompany_click(Object sender, EventArgs e)
{
bool removeSuccess = false;
string idToDelete = ((LinkButton)sender).CommandArgument as string;
removeSuccess = UserInfo.DeleteCompany(idToDelete);
if (removeSuccess)
{
Response.Redirect(Request.RawUrl);
}
}
Here was the issue:
When the LinkButton is clicked, the first thing that happens is the page reloads. However, Response.Redirect(Request.RawUrl) doesn’t preserve the ViewState, so the sort order is lost. Therefore, the GridView is repopulated with unsorted data.
Then, the LinkButton onClick event function is called. The Object passed in is the LinkButton from the correct row number, but since the sort order of the table had changed (back to its unsorted state), the LinkButton in that row was no longer the LinkButton the user had clicked. Therefore, the command argument was wrong.
To fix the issue:
I changed all the ViewState[string] to Session[string] (so that the sort direction is preserved when the page reloads), and added the following code in the Page_Load function, before the GridView is bound:
if (Session["companiesExpression"] != null
&& Session["companiesDirection"] != null)
{
companies.DefaultView.Sort = Session["companiesExpression"] + " " +
Session["companiesDirection"];
}

Dropdownlist in gridview not firing selectedindex changed event

I have problem with not firing selected index changed event of dropdownlist in gridview. I gone through the SO Thread . It is not worked wholly for me. I have implementation like below.
.ASPX
<asp:DropDownList ID="DDL1" runat="server" AutoPostBack="true" OnSelectedIndexChanged="DDL1_SelectedIndexChanged">
<asp:ListItem Text="Review" Value="Review" Selected="True">Review</asp:ListItem>
<asp:ListItem Text="Level1" Value="lvl1">Send Back to Level1</asp:ListItem>
</asp:DropDownList>
.CS
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
// Bind the GridView to something.
DataBindGrid();
}
else {
// Bind the GridView again to maintain previous entered data in the gridview
DataBindGrid();
}
}
protected void DDL1_SelectedIndexChanged(object sender, EventArgs e)
{
this.lblCity.Text = ((DropDownList)sender).SelectedValue;
}
protected void grdPoll_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(Page.IsPostBack)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddl = e.Row.FindControl("DDL1") as DropDownList;
if(ddl != null)
{
ddl.SelectedIndexChanged += new EventHandler(DDL1_SelectedIndexChanged);
}
}
}
}
When i keep if(!Page.IsPostBack) block only then it works fine. But i want else block also. Whats going wrong with implentation. Can you please suggest the solutions
The problem is block after !Page.IsPostBack block, which is not event else part as you said. You are binding grid again on post back which results in loss of the event being fired. You do not have to bind it again to have the changes in the grid.
Remove this code.
{
// Bind the GridView again to maintain previous entered data in the gridview
DataBindGrid();
}
Try this:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
// Bind the GridView to something.
DataBindGrid();
}
else {
// Bind the GridView again to maintain previous entered data in the gridview
//DataBindGrid(); //remove DataBindGrid(); from else
}
}
protected void DDL1_SelectedIndexChanged(object sender, EventArgs e)
{
this.lblCity.Text = ((DropDownList)sender).SelectedValue;
DataBindGrid();
}
replace event name "Page_Load" with "Page_PreRender"

Preserving user control on autopostback asp.net

I have two user controls: dsucTopLeft and dsucTopRight in an aspx page. Each of the user controls has a dropdownlist to select values from.
The aspx page has a button "Save".
In the OnClickEvent of the button, I take data from those user controls (which return the values from the drop down list). I need to insert these values into database. However, these values set to 0 after the button is clicked.
How would I preserve those values?
Code:
ParentTemplate.aspx
<div class="leftDashboard">
<uc:dsuc ID="dsucTopLeft" runat="server" />
</div>
<div id="rightDashboard">
<uc:dsuc ID="dsucTopRight" runat="server" />
</div>
It also has a button:
<asp:Button ID="SaveButton" runat="server" OnClick="SaveButton_Click" Text="Save Dashboard" />
This is the codebehind for the button:
protected void SaveButton_Click(object sender, EventArgs e)
{
//If the mode is "CREATE", then it needs to insert the information about dashboard and the charts it contains
for (int i = 0; i < dsuc.Length; i++)
{
dsuc[i].dashboardId = dashboardId;
if (dsuc[i].chartId != 0) //Here, the chartId remains 0
dsuc[i].insert();
}
}
dsuc is an array. It is being populated in the following way:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
dsuc[0]=dsucTopLeft;
dsuc[1]=dsucTopRight;
}
}
UserControl:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
initializeDropDownList();//It initializes the drop down list
}
}
public void insert()
{
//It inserts into database
}
protected void chartDDLSelectedIndexChanged(object sender, EventArgs e)
{
oldChartId = chartId;
String chartTitle = chartDropDownList.SelectedItem.Text;
if (chartTitle != dropDownMessage)
{
chartId = int.Parse(chartDropDownList.SelectedItem.Value);
//Chart user control should be retrieved from the database and drawn.
chartTitleLabel.Text += "chart id : " + chartId.ToString() + " title: " + chartTitle;
//chartUserControl.Visible = true;
}
}
The user control i.e. the class of dsuc[] changes its chartId when an item in its drop down list is selected. I printed the value, it works. But that same value becomes 0 when the button in clicked.
Remove the if (!Page.IsPostBack)from
if (!Page.IsPostBack)
{
dsuc[0]=dsucTopLeft;
dsuc[1]=dsucTopRight;
}
If not, it will only populate it when is not post back. As a click produces a post back, you'll want that code being executed :)
Also, it is probably that your clickp event is being called beforeselectedindexchanged`. In that case, the code that sets chartId is not executed (yet) when the click event is fired. You can solve that doing this:
public int ChartId { get { return int.Parse(chartDropDownList.SelectedItem.Value); }}
and calling that property instead. Also, you can use that property in your selectedindexchanged event handler

How to programmatically replace an HyperLinkField in a ASP.NET GridView

I have an ASP.NET Web Forms application. In my application I have a GridView that works smoothly. I have several text fields and the last one is a <asp:hyperlinkfield>.
Now I would like to programmatically change the field by placing a simple link instead of the hyperlinkfield if a specific condition is fulfilled. Therefore I catch the onRowDataBound event:
Sub myGridView_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs) Handles myGridView.RowDataBound
If (condition) Then
Dim link = New HyperLink()
link.Text = "login"
link.NavigateUrl = "login.aspx"
e.Row.Cells(3).Controls.Add(link)
End If
End If
End Sub
where n is the cell where the hyperlinkfield is placed. With this code it just adds to the hyperlinkfield the new link. How can I replace it?
PS: The code is in VB6 but I am a C# programmer, answers with both languages are accepted
Remove the control you want to replace from the collection before adding the new one:
protected void TestGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink newHyperLink = new HyperLink();
newHyperLink.Text = "New";
e.Row.Cells[3].Controls.RemoveAt(0);
e.Row.Cells[3].Controls.Add(newHyperLink);
}
}
But I agree with the others, just change the existing link's properties:
protected void TestGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink link = e.Row.Cells[0].Controls[0] as HyperLink;
if (link != null)
{
link.Text = "New";
link.NavigateUrl = "New";
}
}
}
In situations like that I typically convert the bound field to a templated field.
<asp:TemplateField HeaderText="Title" SortExpression="Title">
<ItemTemplate>
<asp:HyperLink ID="TitleHyperLink" runat="server" ></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
And do the rest of the work in the codebehind.
protected void grid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var link = (HyperLink)e.Row.FindControl("TitleHyperLink");
if (link != null)
{
if (condition)
{
link.Text = "login";
link.NavigateUrl = "login.aspx";
}
else
{
link.Text = "default text";
link.NavigateUrl = "default.aspx";
}
}
}
}
Instead of creating a new link at this point, grab the link that's already generated as part of the field.
If (e.Row.RowType = DataControlRowType.DataRow) Then
Dim link = e.Row.Cells(3).Controls(0)
link.Text = "login"
link.NavigateUrl = "login.aspx"
End If
EDIT: Added If block to avoid action outside item rows.
You could do this in your aspx file :
<asp:HyperLink Text='<%# condition ? "TextIfTrue" : "TextIfFalse" %>' NavigateUrl='<%# condition ? "UrlIfTrue" : "UrlIfFalse" %>' />
or cast your
e.Row.Cells(3).Controls(0)
into a hyperlink and change its values.
You can use in the aspx:
<asp:HyperLink ID="HyperLink1" CssClass="exercise" runat="server" NavigateUrl="#">Search ¡here!</asp:HyperLink>
In the codebehind:
You can use also a method:
public string SharePoint(string x)
{
string page1, page2;
if (x== "1")
{
string page1="http://nwpage/files.zip";
return page1;
}
else
{
string page2="http://example2.aspx";
return page2;
}
}
If I call the control in the other method or page load, you can add HyperLink1 with the path
string path= SharePoint(x);
HyperLink1.NavigateUrl = path;

Resources