Wednesday, November 25, 2009

Repeater Hyperlink navigate with condition

Let say, we have a repeater to display the sql table data. When Somebody search in web page it displays the title field data with hyperlink to go to details page.

We can do like this way:

<asp:Repeater>
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%#DataBinder.Eval(Container.DataItem,"Identifier","TitleDetail.aspx?Identifier={0}" ) %>'> <%# DataBinder.Eval(Container.DataItem,"Title")%></asp:HyperLink>
</ItemTemplate>
<FooterTemplate> </FooterTemplate>
</asp:Repeater>

It works fine for a single detail page.

but

let say, I want to go to details page according to the identifier's value.

The Identifier is also from the database. It consists combination of characters and numbers(IM234, MC45, XY67). All the identifiers have same characters but different numbers like (IM234, IM235..., MC45,MC46...XY67,XY68...)

I want to naviagate the page with repect to these identifers e.g

if identifiers contains IM, go to titleIMdetails.aspx? identifier={0}

if identifiers contains MC go to titleMCdetails.aspx ? identifier={0}

[The purpose of this is to have separate header for IM, MC identifiers]

We can handle this way:

Put this code in your aspx page:

<asp:Repeater>
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='&lt;%#returnURL(DataBinder.Eval(Container.DataItem, "Identifier"))%>'><%# DataBinder.Eval(Container.DataItem,"Title")%></asp:HyperLink>
</ItemTemplate>
<FooterTemplate> </FooterTemplate>
</asp:Repeater>

In Aspx.cs page:

protected string returnURL(object paramID)
{

string m_paramID;
m_paramID = (string)paramID;
string retURL = "";
if (m_paramID.Contains("IW"))
retURL = "IWTitleDetail.aspx?Identifier=" + paramID;
else
retURL = "MsTitleDetail.aspx?Identifier=" + paramID;
return retURL;
}

Happy Coding !!!

Thursday, November 5, 2009

Unable to cast object of type system.DBNull to type system.string

Last week, I got this error when I was working on my web apps.

The code which has error:

protected string returnURL(object paramID)
{

string m_paramID;
m_paramID = (string)paramID;
string retURL = "";
if (m_paramID.Contains("IWA"))
retURL = "IWTitleDetail.aspx?Identifier=" + paramID;
else
retURL = "MsTitleDetail.aspx?Identifier=" + paramID;

return retURL;
}

Then, I changed to this and it solved the problem:

protected string returnURL(object paramID)
{
string retURL = "";
string m_paramID;
if (paramID == DBNull.Value)
{ }
else
{
m_paramID = (string)paramID;
if (m_paramID.Contains("IWA"))
retURL = "IWTitleDetail.aspx?Identifier=" + paramID;
else
retURL = "MsTitleDetail.aspx?Identifier=" + paramID;
}

return retURL;
}

Happy Coding!!