Show and Hiding information in ASP.NET data grid - c#

i have a datagrid which contains a lot of information in one column.
I would like a way for the user to preview some of the content in that column and then click a "more" hyperlink in that column that takes them to another page that displays all the information in that column allowing them to add more info into it and other items in that row.
I have done the more hyper link on the end of all the information but i would i change for example:
"HI my name is stefan i like walking on the beach and other stuff...more"
to
"Hi my name is stefan... more"
And how would i pull up the selected row in an new datagrid on a new asp page after they click more?
When i click the more hyperlink it doesn't open the correct row but only blogid 2.

you can use HyperLink in GridView. You can use CommangArgument and CommandName Property to Hold the specic data. When u clicked the hyperlink the data will be passed as querystring to the next page. so that you can use the querytring
And to display " ... more" you can use substring method.. substring for a legnth and concat the ....more to your hyperlink text.
MSDN for CommandArgument
Sample for Passing data with LinkButton

Handle OnRowDataBound as so:
protected void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
// say for example that the column with long text is the 5th one
e.Row.Cells[5].Text = e.Row.Cells[5].Text.Length>20?e.Row.Cells[5].Substring(0,20)+" more...";
}
}
Where the first column (Cells[0]) has the blog ID. I think that's how you have your gridview now.

I think maybe you're looking for the text-overflow: ellipsis; CSS styling. You can then use jQuery or plain javascript to toggle the style and reveal all the text.
I'm not quite sure how this is handled by Firefox today, but IE is ok.

I managed to fix this by using an sql query,
Left(content,50)
Which displays the first 50 characters.

You can try following code:
<asp:TemplateField HeaderText="Description" HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="Left">
<ItemTemplate>
<%# (Eval("strDescription").ToString().Length > 55 ? Eval("strDescription").ToString().Substring(0, 55) + "....." : Eval("strDescription"))%>
</ItemTemplate>
</asp:TemplateField>
and just add hyperlink in this item template and assign your blogid(in your case) to that hyperlink to open detail page that you want.

Related

How to create editable GridView with dynamic controls

How do I create editable gridviews with dynamic controls. The following image gives an idea.
On page load, a gridview will be shown with only a single row other than the header. The row contains two dropdownlist, two textboxes and an image button. Once I enter data in the first row, and then press the image button, a new row with these controls will be created, and so on.
How is this possible?
Gridview by default does not provide a simple way of handling the Insert operations.
You will have to perform several steps to handle this.
First of all each gridview column has to be converted to TemplateColumn(TemplateField). Then in the footer template you have to insert your controls(dropdown, textbox etc.)
<asp:TemplateField HeaderText="Item Category">
<%--Define item template--%>
<FooterTemplate>
<asp:DropDownList ID="dropDownListCategory" runat="server"></asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
...... similarly other footer templates
You have to add the onclick Event for the ImageButton.
protected void imageButtonInsert_Click(object sender, EventArgs e)
{
//Get the gridview row
GridViewRow row = (sender as Control).NamingContainer as GridViewRow;
DropDownList dropDownListCategory = row.FindControl("dropDownListCategory") as DropDownList;
///Similarly you can access the other controls here
//If you are using SqlDataSource then you can add/assign these values to the insert parameters
//Note that, you need to have insertcommand defined for the sql data source with appropreate parameters
SqlDataSource1.InsertParameters.Add("category", dropDownListCategory.SelectedValue);
//Similarly assign the other parameter values
//Call the insert method of the sql data source.
SqlDataSource1.Insert();
//If you are not using data source approach, here you can insert the data to
// database by calling sql command or other ways
//Rebind the gridview.
GridView1.DataBind();
}
This should work, when you have some rows to display in the gridview.
BIG PROBLEM : EMPTY ROWS
The above approach works when you have at least one row in the gridview. But if you do not have any rows, that is for the first time, the gridview will be empty. If the gridview data source is empty, then it does not display anything, even header,footer, rows etc.
As a initial workaround, first you need to make the header is always visible
ShowHeaderWhenEmpty="true" ShowFooter="true"
This makes sure that you have the headers all the time.
Now footer will not at all display unless and until there is some row in the gridview.
As a work around you can use EmptyDataTemplate of the gridview.
Here you need to add all your controls again, dropdownlist, textboxes etc. Not that you have to use here to make the same layout. You can use the same control ids, so that you dont need to write the codebehind again
<EmptyDataTemplate>
<tr>
<td><asp:DropDownList ID="dropDownListCategory" runat="server"></asp:DropDownList></td>
<td><asp:Button runat="server" CommandName="Insert" ID="buttonInsert" OnClick="imageButtonInsert_Click" Text="Insert" /></td>
<%--Other controls go here--%>
</tr>
</EmptyDataTemplate>
This is now good for both first time and successive load.
The next question you may have is how to bind these dropdowns. For this you need to use the RowCreated event, in which you can access the dropdowns and fill them
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer || e.Row.RowType == DataControlRowType.EmptyDataRow)
{
DropDownList dropDownListCategory = e.Row.FindControl("dropDownListCategory") as DropDownList;
//similarly access the other controls and bind them
}
}
For Doing this use can use Dynamic table at client side. where you can create whole table dynamically and also apply styling that can look like grid view. for Styling use can use JQuery DataTables which provice much more controls.
And also by using JQuery DataTables or JQuery Code you can also add rows dynamically at client side.

How do I use the RowCreated event for GridViews

Problem:
I want to add headers in the middle of a gridview databind. I updated the DataTable to include headers and their correct positions(I've checked during debug, they're there). On the new rows that contain headers, one of the unneeded fields (unneeded as in the header doesn't need that information) has a flag called "Subheader" in it.
Background information:
So my datatable rows hold a server name, and the group the server belongs to. I updated the DataTable so it inserts a new row where the server name is the header text. The server group that this new row belongs to is "Subheader". My datatable holds more information than what my gridview shows. My gridview only needs one column, but has a column with visibility=false; which holds the server group.
What I want to achieve:
So when I bind this datatable to the gridview I want all the non-header rows to be links that point to another location. All the data rows that are headers I want to just leave them as is.
Code:
private void CurrentServers_RowCreated(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if(e.Row.Cells[1].Text != "Subheader")
{
e.Row.Cells[0].Text = "<a href='/EventViewer.aspx?m=" + e.Row.Cells[0].Text + "&s=&e=Application&r=25'>" + e.Row.Cells[0].Text + "</a>";
}
}
}
Questions:
This isn't working. e.Row.Cells[1].Text != "Subheader" always returns true. In debugging I check the value of e.Row.Cells[1].Text and somewhere in there it has the information I need.
Is this the correct event I should be handling?
How do I access that data? e.Row.Cells[1].Text and e.Row.Cells[1].ToString() do not return the result that I want, even though when in debugging I can find the value I want in e.Row
I've tried finding exactly how this works but am unable to find answers. If my GridView only has columns for 2 datatable columns, will e.Row.Cells only have the 2 cells that my gridview requires, or does this take place before it breaks apart the datatable (i.e. does it have all the columns that my datatable has)
Depending on how you bind your data and how you get server group, you could do the following:
In the item template where you're showing content of nonheader row, instead of plain text use two placeholders, one will hold label for nonhyperlink text and another will hold hyperlink. You bind both controls to whatever text property you use. And set those placeholders' visibility to Eval("ServerGroup").ToString().ToLowerInvariant().Equals("subheader") and !Eval("ServerGroup").ToString().ToLowerInvariant().Equals("subheader"). That way you won't have to write code to perform control manipulation and get away from using RowDataBound event all together.
Let me know if this doesn't make sense :)
EDIT:
<asp:GridView ID=".." runat="server" ...>
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:PlaceHolder id="phTextContent" runat="server" visible='<%# Eval("ServerGroup").ToString().ToLowerInvariant().Equals("subheader") %>'>
<asp:Label id="lblServerGroup" runat="server" text='<%#Eval("ServerGroup")%>'/>
</asp:PlaceHolder>
<asp:PlaceHolder id="phTextContent" runat="server" visible='<%# !Eval("ServerGroup").ToString().ToLowerInvariant().Equals("subheader") %>'>
<asp:HyperLink id="hlServerGroup" runat="server" Text='<%#Eval("ServerGroup")%>' NavigateUrl='<%#string.Fromat("/MyAction.aspx?param=", Eval("Param"))%>'/>
</asp:PlaceHolder>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

Get the value of a column that is using a ButtonField

I have a GridView and one of the columns has a TemplateField using a LinkButton (ButtonField)
I can get the value of a specific cell in my Grid Just fine. Using:
GridViewRow row = GridView1.SelectedRow;
lblSalesmanCustomers.Text = row.Cells[2].Text;
I then display the text from that cell in a Label.
However I cannot get this to work with a ButtonField Template. It only works with a non Template column.
How can I get the value of a specific cell in a column that is using a ButtonField / TemplateField?
EDIT: This is My Button Field Code inside my GridView:
<asp:ButtonField DataTextField="Customer" HeaderText="Customer" ButtonType="Link" CommandName="Select" />
Also, this is happening in this event:
protected void gvManagerCustomers_SelectedIndexChanged(object sender, EventArgs e)
See if var Button = row.Cells["Customer"].Controls[0]; would retrieve the button you need.
You might need to cast it to the correct type.
I know there are issues with hyperlinkfield and buttonfield but there is a work around. Say you are binding buttonfield text based on a column called ButtonNames, and in that column you have all your names, such as "button bob", "button jerry" etc. In your GridView, add an invisible column as your very first column and bind its value as ButtonNames. You make it invisible by setting one of the visibility properties. Forgot what it was from top of my head. Then, when you want to get the text for the buttonfield simply get the data from that invisible column instead Same applies to hyperlinkfiends.
EDIT: here's some code.
<asp:BoundColumn ItemStyle-HorizontalAlign="Left" DataField="ButtonNames" SortExpression="ButtonNames" HeaderText="TriageId" Visible="false" ReadOnly="true"></asp:BoundColumn>
Then you retrieve it via string s = e.Item.Cells[0].Text where e is a DataGridCommandEventArgs or something to that nature.
There will be a controls collection in the cell - you may be able to access it there.
Though a simpler way would be to use something like:
Label l = row.FindControl("myControlId");
EDIT: true the exact approach above does not work - but you can use the controls, the following does work, note that what we are doing here is pretty much rife with bad practices (but then we are using a GridView for convenience sake after all).
protected void gvManagerCustomers_SelectedIndexChanged(object sender, EventArgs e)
{
var x = ((sender as GridView).SelectedRow.Cells[0].Controls[0] as LinkButton).Text;
}
In order to figure this out set up a debug environment and breakpoint in the handler method then drill down through the class hierarchy. The debugger is our friend ;)
EDIT just to mention the obvious - the column is hard coded here - you will probably have to change it.

Changing text of an autogenerated select column of a gridview in asp.net - How?

I would like to change the text of the autogenerated "select" column in an ASP.NET GridView control. The text needs to be changed to the value of a DataField.
I suspect that there is a very logical way to do this but I am missing it.
I am able to add controls and data via the pre-render event but is there an easier better way?
Use the TemplateField and place into it buttons or linkbuttons with appropriate CommandName property: ButtonField.CommandName Property
You may set this button text using DataBinder.Eval method.
The easiest way I found to do this is after the calling DataBind() just before the gridview control is displayed.
foreach (GridViewRow row in gvAgreementList.Rows)
{
LinkButton lb = (LinkButton) row.Cells[0].Controls[0];
lb.Text = "Edit";
}
after <column> write this:
<asp:CommandField ShowSelectButton="True" SelectText="Save" />
and remove AutoGenerateSelectButton="True" from Gridview attribute.
First remove auto generated select then go to GridView tasks.. top right Button of GridView and then click on commandfields -> Select then edit SelectText.
(Edited answer of ShaileshK with some changes)
Go to GridVIew tasks.. top right Button of GridView and then click on edit columns
In selected fields section Click on select field. change the value of select text.
done.

Disable gridview link on rows where field is not null?

I've got an asp gridview where I want to disable the edit hyperlink field on rows where the status field is anything but "New". What logic do I need for this?
It's been a while, but I think you need to attach onto the RowDatabound event of the GridView and then access that hyperlink to disable it based on the data used for that row.
Add in a template field and simply put in this condition:
<asp:TemplateField HeaderText="Edit">
<asp:LinkButton ID="LinkButton1" Text="Edit" runat="server" Enabled='<%# Convert.ToString(Eval("Status")) == "New" ? true : false %>'></asp:LinkButton>
</asp:TemplateField>
You can use the RowDataBound method of the GridView. Within this, you can then check the value of your status field, and then either hide or disable the Hyperlink.
I used something once. It is not the best practice but it worked for me.
BTW I used it an Edit Button not in an Edit Text but i think it has to work as the same way.
In the RowDataBound Event of the GridView use this:
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Use the index of your Edit Cell
if(bool.Parse(DataBinder.Eval(e.Row.DataItem, "Status"))
{
e.Row.Cells[8].Controls.Clear();
}
}

Categories

Resources