Showing url in BoundField in gridview - asp.net

I am developing a chatting web application with the help of the gridview....The problem is when the user enter the link and it is saved in the database and when the data is retrieved in the gridview the link should be click able. The field I am using to retrieve the data is BoundField.
I don't want to use hyperlink field because then in every row there will a link. I only want to display link when a user will enter a link.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="AccessDataSource1" CssClass="amit1" >
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<asp:BoundField DataField="m1" HeaderText="Message" SortExpression="m1" >
<HeaderStyle Font-Size="Larger" HorizontalAlign="Left" Width="280px" />
<ItemStyle Font-Size="Medium" HorizontalAlign="Left" Width="280px" />
</asp:BoundField>
</Columns>
</asp:GridView>
<asp:AccessDataSource ID="AccessDataSource1" runat="server"
DataFile="~/App_Data/gold.accdb"
SelectCommand="SELECT [m1] FROM [Chat_detail] WHERE ([Chat_id] = ?)">
<SelectParameters>
<asp:QueryStringParameter Name="Chat_id" QueryStringField="chat_id"
Type="String" />
</SelectParameters>
</asp:AccessDataSource>
Is there is any way to do this???
Thanks in advance.

Add Hyperlink, make use of RowDataBound event to make that hyperlink visible tru/false based on the value.
See Below:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink hlnk = (HyperLink)e.Row.FindControl("hlnkUserEnetredLink");
if(!String.IsNullOrEmpty(hlnk))
{
hlnk.Visible = true;
}
else
{
hlnk.Visible = false;
}
}
}
Add that Hyperlink in your aspx page -- in Gridview..

You could disable the hyperlink in your code behind based on whatever condition. Note: Making visible = true/false will leave a empty cell in the gridview column.
protected void GridView1_DataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// find the HyperLink defined in the fridview definition
HyperLink myHyperLink = (HyperLink)e.Row.FindControl("hpLinkUrl");
//userstoredlink is the datasource field that holds the user stored link
string userLink = DataBinder.Eval(e.Row.DataItem, "userstoredlink").ToString();
if (string.IsNullOrEmpty(userLink))
{
// disable link
myHyperLink.Enabled = false;
}
}
}
Please refer my another post on different ways to add hyperlink to gridview
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink ID="hpLinkUrl" runat="server" NavigateUrl='<%# Eval("userstoredlink", "{0}") %>' Text="View Details" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
Also remember you need to define OnRowDataBound="GridView1_RowDataBound" for your gridview.
Or if you don't want to display the ViewDetails text when there is no value for userstoredlink then changes the hyperlink definition as follows
<asp:HyperLink ID="hpLinkUrl" runat="server" NavigateUrl='<%# Eval("userstoredlink", "{0}") %>' Text='<%# Eval("userstoredlink") != "" ? "View Details" : "" %>' />

Related

Dynamic button in gridview ASP.NET c#

i have a grid view in Asp.net. i want to generate button for specific rows.
Like i have a column named as "Status". If status is "Accept" a button should be generated in that particular row.
column
You can use a TemplateField in ASP.NET GridView and conditionally set the Button visibility, like shown below:
<asp:GridView runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Status" HeaderText="Status" />
<asp:TemplateField>
<ItemTemplate>
<asp:Button runat="server" Text="Accept"
Visible='<%# Eval("Status")=="Accept" %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Hope this will help.
first add template field button like this
<asp:TemplateField HeaderText="status" ShowHeader="False">
<ItemTemplate>
<asp:Button ID="btn" runat="server" CausesValidation="false"
CommandName="Select" Text="button" />
</ItemTemplate>
</asp:TemplateField>
and codebehind
protected void grid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Button btn = (Button)e.Row.FindControl("btn");
if (e.Row.Cells[1].Text == "Accept")//replace 1 by your column(status) index in gridview
{
btn.Visible = true;
}
else
{
btn.Visible = false;
}
}
}
and to add code to this button so add it on
protected void grid_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
//code
}

Findcontrol failed for templatefield (linkbutton) in detailsView

I would like to set a templatefield (linkbutton) to invisible when the DetailsView is not in ReadOnly mode. I created a linkbutton to replace the auto-gen "delete" button and want to hide it when editing and inserting.
<asp:DetailsView ID="resultDetailsView" runat="server" AutoGenerateRows="False" DataKeyNames="smo_code,id"
DataSourceID="detailviewDataSource" Height="50px" Width="125px" OnItemInserting="resultDetailsView_ItemInserting"
OnItemUpdating="resultDetailsView_ItemUpdating" OnItemUpdated="resultDetailsView_ItemUpdated"
OnItemDeleted="resultDetailsView_ItemDeleted" OnItemInserted="resultDetailsView_ItemInserted"
OnItemDeleting="resultDetailsView_ItemDeleting" OnModeChanging="resultDetailsView_ModeChanging"
OnDataBound="resultDetailsView_DataBound" OnItemCommand="resultDetailsView_ItemCommand">
<Fields>
<asp:BoundField DataField="event" HeaderText="event" SortExpression="event" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="deleteLink" runat="server" CommandName="Delete" Text="Delete"
OnClientClick='return confirm("Are you sure you want to delete this item?");' />
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowDeleteButton="False" ShowEditButton="True" ShowInsertButton="True" />
</Fields>
</asp:DetailsView>
IN CODE BEHIND, FINDCONTROL returned null:
protected void resultDetailsView_DataBound(object sender, EventArgs e)
{
LinkButton deleteLink = (LinkButton)resultDetailsView.FindControl("deleteLink");
if (resultDetailsView.CurrentMode == DetailsViewMode.ReadOnly)
{
deleteLink.Visible = true;
}
else
{
deleteLink.Visible = false;
}
}
You can do it after .DataBind() method. Here is a good example
How to dynamically hide fields in a DetailsView (fields count is always 0)
Or even this too is a good example
Listview/DetailsView: Hide a null field

GridView DataBind does not work

I am using ASP.NET Membership and Linq. I have a problem here: I show all users inside a grid view that has a delete button. Take a look at this code:
<asp:GridView
ID="UsersGridView"
runat="server"
AutoGenerateColumns="False"
DataSourceID="UsersLinqDataSource"
AllowPaging="True">
<Columns>
<asp:BoundField DataField="UserName" HeaderText="UserName" ReadOnly="True" SortExpression="UserName" />
<asp:BoundField DataField="LastActivityDate" HeaderText="LastActivityDate" ReadOnly="True" SortExpression="LastActivityDate" />
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="DeleteButton" runat="server" CommandArgument='<%# Eval("UserName") %>' Text="Delete" OnClick="DeleteButton_Click"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:LinqDataSource
ID="UsersLinqDataSource"
runat="server"
ContextTypeName="TraceWeb.DataModel.DataContextDataContext"
EntityTypeName=""
Select="new (UserName, LastActivityDate)"
TableName="Users"
EnableDelete="True">
</asp:LinqDataSource>
And Delete button's event handler:
protected void DeleteButton_Click(object sender, EventArgs e)
{
String username = (String)((sender as IButtonControl).CommandArgument);
Membership.DeleteUser(username, true);
UsersGridView.DataBind();
}
But problem is that after running this code and deleting a user, GridView still shows that user.
This happens because Membership and UsersLinqDataSource are not connected and if you "refresh" the UsersLinqDataSource status and then rebind your grid, all will be displayed properly.
protected void DeleteButton_Click(object sender, EventArgs e)
{
String username = (String)((sender as IButtonControl).CommandArgument);
Membership.DeleteUser(username, true);
// first solution: may not work properly
UsersLinqDataSource = yourLinqData;
// second solution: work
UsersLinqDataSource = null;
UsersLinqDataSource = yourLinqData;
UsersGridView.DataBind();
}

Edit button text in GridView

Q> I want to show a GridView button's text as hard coded and a event to fire on button click. How to achieve this ?
Till now I've been able to come this far
But I want to show button text as Read or Delete not the value in the Read/Delete column.
The code I've used
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="MID" DataSourceID="inbox" EnableModelValidation="True"
onselectedindexchanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:ButtonField ButtonType="Button" DataTextField="MID" HeaderText="Read"
Text="Read" />
<asp:BoundField DataField="MID" HeaderText="MID" InsertVisible="False"
ReadOnly="True" SortExpression="MID" />
<asp:BoundField DataField="sender" HeaderText="sender"
SortExpression="sender" />
<asp:BoundField DataField="subject" HeaderText="subject"
SortExpression="subject" />
<asp:BoundField DataField="on" HeaderText="on" SortExpression="on" />
<asp:ButtonField ButtonType="Button" DataTextField="MID" HeaderText="Delete"
Text="Delete" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="inbox" runat="server"
ConnectionString="<%$ ConnectionStrings:connectionString %>"
SelectCommand="SELECT [MID], [sender], [subject], [on] FROM [mail]">
</asp:SqlDataSource>
If you want the text to appear as "Delete" or "Read", then simply don't set the DataTextField property to use the MID property of the result and instead set the CommandName property as so:
<asp:ButtonField ButtonType="Button" CommandName='<%#Eval("MMID")%>' HeaderText="Delete"
Text="Delete" />
As far as handling the OnClick event of the buttons, you can handle the OnRowCommand event on the GridView as so:
<asp:GridView ID="GridView1" runat="server" OnRowCommand="GridView_RowCommand" AutoGenerateColumns="False"
Now add the code behind:
protected void GridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
string MMID = e.CommandName;
if( (e.CommandSource as ButtonField).Text=="Delete")
{
//oh, I should delete this MMID
}
}
UPDATE
Above code does not work. ButtonField is as useful as nipples are to men. Instead use an ItemTemplateField as so:
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btn" runat="server" CommandName="Delete" CommandArgument='<%#Eval("MID") %>'
Text="Delete" />
</ItemTemplate>
</asp:TemplateField>
Then the GridView_RowCommand becomes this:
protected void GridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
string mid = e.CommandArgument.ToString();
// If multiple buttons are used in a GridView control, use the
// CommandName property to determine which button was clicked.
if (e.CommandName == "Delete")
{
}
}

ASP.NET Grid View Problem

I have one gridview where I am passing the command argument as gridview row id for the Button I created for every row.
I want to display all the details of that row in the textbox according to the Row clicked.
<asp:GridView ID="gvCategory" runat="server" AutoGenerateColumns="false"
onrowcommand="gvCategory_RowCommand" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblCatId" runat="server" Text='<%#Eval("categoryId") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblCatName" runat="server" Text='<%#Eval("categoryName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnModify" runat="server" Text="Modify" CommandName="Modify" CommandArgument='<%#Eval("categoryId") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code.....
if (e.CommandName == "Modify")
{
int id = Convert.ToInt32(e.CommandArgument);
// I want the value to assgin for the selected row here
// I was previously fetching the data from database according id,but i want this frim the gridview of selected row.
}
I wrote a quick example of how to do what you're trying to do. It works for me.
The Example Solution
Default.aspx
<asp:GridView ID="myGridView" runat="server"
AutoGenerateColumns="False"
DataSourceID="StudentsDS"
DataKeyNames="ID"
OnRowCommand="myGridView_RowCommand"
OnSelectedIndexChanged="myGridView_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True"
SortExpression="ID" />
<asp:BoundField DataField="FullName" HeaderText="FullName"
SortExpression="FullName" />
<asp:BoundField DataField="ClassID" HeaderText="ClassID"
SortExpression="ClassID" />
<asp:CommandField ShowSelectButton="True" SelectText="Modify" />
</Columns>
</asp:GridView>
<asp:TextBox ID="txtStudent" runat="server" />
<asp:SqlDataSource ID="StudentsDS" runat="server"
ConnectionString="<%$ ConnectionStrings:Sandbox %>"
SelectCommand="SELECT * FROM Student"
/>
Default.aspx.cs
protected void myGridView_RowCommand(object sender, GridViewCommandEventArgs e) {
if (e.CommandName == "Select") {
// do something here if you want, although not necessary
}
}
protected void myGridView_SelectedIndexChanged(object sender, EventArgs e) {
// show "FullName" field of selected row in textbox
txtStudent.Text = myGridView.SelectedRow.Cells[1].Text;
}
How It Works
Upon clicking "Modify" in a row, the textbox updates to show the FullName field of the selected row.
The important part is that instead of a TemplateField, use a CommandField with ShowSelectButton="True". Then do what you need to do in the SelectedIndexChanged event handler. Note that the SelectText of the CommandField is set to "Modify" as you desired. You can also set the ButtonType property of the CommandField to be button, image, or link.
Making It Better
I would also advise that instead of using a SqlDataSource as I have, you use an ObjectDataSource so that you can do something like
protected void myGridView_SelectedIndexChanged(object sender, EventArgs e) {
MyModelObject o = myGridView.SelectedRow.DataItem as MyModelObject;
txtStudent.Text = o.MyProperty;
}
You may also consider wrapping your GridView in an UpdatePanel to prevent full postbacks / page refreshes.
After you have the lineID, you select that line, and then you have the CategoryID on selected value
int iTheIndexNow = Convert.ToInt32(e.CommandArgument);
// select that line to see it visual as selected, and get the value on next line
gvCategory.SelectedIndex = iTheIndexNow;
// here is your categoryID that
//you can use to open your database with and get the text
gvCategory.SelectedValue // == categoryID
On GridView you must have set your KeyID
<asp:GridView DataKeyNames="categoryId" .... >

Resources