reverse asp.net grid view columns header into rows header - c#

I'm still learning asp.net and I want to ask you about how to reverse the grid view, I mean the default grid view would be like this
and this is the code for it:
<asp:GridView ID="GridView1" runat="server" EnableModelValidation="True"
AutoGenerateColumns="false" Width="256px">
<Columns>
<asp:TemplateField HeaderText="1"> <ItemTemplate>
<asp:Label ID="test1" runat="server" Text="test1"></asp:Label>
</ItemTemplate></asp:TemplateField>
<asp:TemplateField HeaderText="2"> <ItemTemplate>
<asp:Label ID="test2" runat="server" Text="test2"></asp:Label>
</ItemTemplate></asp:TemplateField>
<asp:TemplateField HeaderText="3"> <ItemTemplate>
<asp:Label ID="test3" runat="server" Text="test3"></asp:Label>
</ItemTemplate></asp:TemplateField> </Columns>
<RowStyle HorizontalAlign="Left" VerticalAlign="Bottom" />
</asp:GridView>
and i want it to be like this picture :
the test here will be data bound and the numbers should be header text, this is only for test, is there a way to reverse it?
thank you all for your valuable advises and efforts, I really appreciate it.

I was able to achieve what I want by pivoting the data table and the columns became rows and the opposite.
this link can explain it.
thx

Related

I like to make all column of radgrid table editable in asp.net c#

How to make all the row cells editable on click of the edit button.
Following is the code snipped. Any help would be appreciated. On click of btnEdit_Click event, i want the radgrid row cells editable so that use can update existing data. i dont want to add inline edit button for each row in radgrid, instead on single edit button, all row cells should be editable based on their data type.
<asp:ImageButton runat="server" ID="btnEdit" ImageUrl="~/images/Buttons/Edit.gif"
OnClick="btnEdit_Click" />
<radG:RadGrid ID="grdAction" runat="server" AllowPaging="True" Width="100%" EnableAJAXLoadingTemplate="true"
CellPadding="1" CellSpacing="1" AllowSorting="True" ShowHeader="false" OnNeedDataSource="grd_View_NeedDataSource"
OnDetailTableDataBind="grd_View_DetailTableDataBind" PageSize="11" MasterTableView-GroupsDefaultExpanded="true"
OnPreRender="grd_View_PreRender" AllowMultiRowSelection="true" MasterTableView-EditFormSettings-EditColumn-AutoPostBackOnFilter="false"
Skin="Glassy" AllowMultiRowEdit="true">
<MasterTableView AutoGenerateColumns="False" HierarchyDefaultExpanded="true">
<AlternatingItemStyle CssClass="GridView-GroupHeaderItemStyle" />
<Columns>
<radG:GridTemplateColumn UniqueName="TemplateColumn" SortExpression="VSGroupBy">
<ItemTemplate>
<asp:Label ID="lblStatus" Visible="false" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, FIRSTGROUP).ToString() %>'> </asp:Label>
<asp:Label ID="lblStatus1" runat="server" Text='<%# GetGroupBy(DataBinder.Eval(Container.DataItem, FIRSTGROUP).ToString()) %>' />
<asp:Label ID="lblcnt" runat="server" Text='' />
</ItemTemplate>
<ItemStyle Width="100%" />
</radG:GridTemplateColumn>
</Columns>
<ExpandCollapseColumn>
<HeaderStyle Width="19px" />
</ExpandCollapseColumn>
<DetailTables>
<radG:GridTableView Width="100%" runat="server" AutoGenerateColumns="False" ShowHeader="True"
HierarchyLoadMode="ServerBind">
<HeaderStyle CssClass="GridView-HeaderStyle" Width="10%" />
<Columns>
<radG:GridTemplateColumn HeaderText="Header1" SortExpression="Header1">
<ItemTemplate>
<asp:Label ID="lblItem1" runat="server" Text='<%# Eval("RootCause").ToString()+ "&nbsp" %>'></asp:Label>
</ItemTemplate>
<ItemStyle VerticalAlign="Top" />
<HeaderStyle Width="22%" Wrap="True" />
</radG:GridTemplateColumn>
<radG:GridTemplateColumn HeaderText="header2" SortExpression="" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lblAgree" runat="server" CssClass='<%# Eval("lblitem2").ToString()=="N"?"AgreeStyles": ""%>' Text='<%# Eval("lblitem2").ToString()+ "&nbsp" %>'></asp:Label>
</ItemTemplate>
<ItemStyle VerticalAlign="Top" />
<HeaderStyle Width="3%" Wrap="True" />
</radG:GridTemplateColumn>
<radG:GridTemplateColumn HeaderText="header3" SortExpression="What">
<ItemTemplate>
<asp:Label ID="lblitem3" runat="server" Text='<%# UIHelper.TextArea2HTML(Eval("lblitem3").ToString())+ "&nbsp" %>'></asp:Label>
</ItemTemplate>
<ItemStyle VerticalAlign="Top" />
<HeaderStyle Width="15%" Wrap="True" />
</radG:GridTemplateColumn>
</Columns>
<PagerStyle Mode="NumericPages" Position="TopAndBottom" />
<EditFormSettings>
<EditColumn UniqueName="EditCommandColumn">
</EditColumn>
</EditFormSettings>
<AlternatingItemStyle CssClass="GridView-ItemStyle" />
<GroupHeaderItemStyle CssClass="GridView-GroupHeaderItemStyle" />
<ExpandCollapseColumn ButtonType="ImageButton" UniqueName="ExpandColumn" Visible="False">
<HeaderStyle Width="19px" />
</ExpandCollapseColumn>
<ItemStyle CssClass="GridView-ItemStyle" />
<RowIndicatorColumn UniqueName="RowIndicator" Visible="False">
<HeaderStyle Width="20px" />
</RowIndicatorColumn>
<NoRecordsTemplate>
There is no document to display
</NoRecordsTemplate>
</radG:GridTableView>
</DetailTables>
<NoRecordsTemplate>
There is no Actions to display
</NoRecordsTemplate>
<ExpandCollapseColumn Visible="False">
<HeaderStyle Width="19px" />
</ExpandCollapseColumn>
<RowIndicatorColumn Visible="False">
<HeaderStyle Width="20px" />
</RowIndicatorColumn>
<ItemStyle CssClass="GridView-GroupHeaderItemStyle" />
</MasterTableView>
<PagerStyle Mode="NumericPages" PageButtonCount="20" />
<HeaderStyle CssClass="GridView-HeaderStyle" />
<GroupHeaderItemStyle CssClass="GridView-GroupHeaderItemStyle" />
<ItemStyle CssClass="GridView-GroupHeaderItemStyle" />
<AlternatingItemStyle CssClass="GridView-GroupHeaderItemStyle" />
<PagerStyle Mode="NumericPages" Position="TopAndBottom" PageButtonCount="20" />
<FilterMenu HoverBackColor="LightSteelBlue" HoverBorderColor="Navy" NotSelectedImageUrl="~/RadControls/Grid/Skins/Default/NotSelectedMenu.gif"
SelectColumnBackColor="Control" SelectedImageUrl="~/RadControls/Grid/Skins/Default/SelectedMenu.gif"
TextColumnBackColor="Window"></FilterMenu>
<ClientSettings>
<Selecting AllowRowSelect="true"></Selecting>
</ClientSettings>
</radG:RadGrid>
Ok, several issues.
You are (it looks like) using a data pager - this can compliate things quite a bit.
Next, you using radgrid - so, a large % of the posters here - they may well not have an answer.
But, I do think the idea of tossing up a grid - let user edit, and then a SINGLE saved for all edits makes a WHOLE lot of sense. In fact, given that UI, then really no need for a edit buttion. all you really need/want is a save button, and then say a cancel/undo edits.
A really neat-o trick for above? Just persist the data source. Once you do that?
Then you allow the user to edit the grid - (no code required).
Then on save, you move grid edits back to the data talbe, and then in ONE NICE EASY update, send the data table back to the database. This results not only in VERY little code, but also provivdes a reather nice and un-cluttered UI to the user.
So, lets use a GridView. In fact, I OFTEN suggest to use a listview.
Why?
Well, with gridview (and the older datagrid), for each column control you drop in, you MUST put that standard control inside of "template" tags - so you require more (messy) markup.
But, lets do this with a simple gridview, and as you can see, not only is this easy, but we ALSO get .net to create the update statetments, and this we "leverage" the built in system to do all the dirty work.
So, say we have this grid:
<style> .borderhide input {border:none}</style>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID"
cssclass="table table-hover borderhide">
<Columns>
<asp:TemplateField HeaderText ="First Name">
<ItemTemplate>
<asp:TextBox ID="txtFirst" runat="server" Text = '<%# Eval("FirstName") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText ="Last Name">
<ItemTemplate>
<asp:TextBox ID="txtLast" runat="server" Text = '<%# Eval("LastName") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText ="City">
<ItemTemplate>
<asp:TextBox ID="txtCity" runat="server" Text = '<%# Eval("City") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText ="Active">
<ItemTemplate>
<asp:CheckBox ID="Active" runat="server" Checked = '<%# Eval("Active") %>'></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="cmdSave" runat="server" Text="Save" CssClass="btn-primary" OnClick="cmdSave_Click1" />
<asp:Button ID="cmdAdd" runat="server" Text="Add Row" CssClass="btn-primary" style="margin-left:20px"/>
<br />
Ok, not much markup.
So, now here is our code to fill the grid:
private DataTable rstPeople = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadGrid();
ViewState["MyTable"] = rstPeople;
Session["test"] = "hello";
}
else
rstPeople = (DataTable)ViewState["MyTable"];
}
public void LoadGrid()
{
using (SqlCommand cmdSQL = new SqlCommand("SELECT * from People",
new SqlConnection(Properties.Settings.Default.TEST4)))
{
cmdSQL.Connection.Open();
rstPeople.Load(cmdSQL.ExecuteReader());
GridView1.DataSource = rstPeople;
GridView1.DataBind();
}
}
Ok, but NOTE how we load the grid, but ALSO save (perist) the data table.
So, we now have this:
Ok, so you are now free to tab around - edit - it feels ALMOST like a spreadsheet.
Now, here is the save button to send the WHOLE set of edits back to database in one shot:
protected void cmdSave_Click1(object sender, EventArgs e)
{
// pull grid rows back to table.
foreach (GridViewRow rRow in GridView1.Rows)
{
int RecordPtr = rRow.RowIndex;
DataRow OneDataRow;
OneDataRow = rstPeople.Rows[RecordPtr];
OneDataRow["FirstName"] = ((TextBox)rRow.FindControl("txtFirst")).Text;
OneDataRow["LastName"] = ((TextBox)rRow.FindControl("txtLast")).Text;
OneDataRow["City"] = ((TextBox)rRow.FindControl("txtCity")).Text;
OneDataRow["Active"] = ((CheckBox)rRow.FindControl("Active")).Checked;
}
// now send table back to database with updates
string strSQL = "SELECT ID, FirstName, LastName, City, Active from People WHERE ID = 0";
using (SqlCommand cmdSQL = new SqlCommand(strSQL,
new SqlConnection(Properties.Settings.Default.TEST4)))
{
cmdSQL.Connection.Open();
SqlDataAdapter daupdate = new SqlDataAdapter(cmdSQL);
SqlCommandBuilder cmdBuild = new SqlCommandBuilder(daupdate);
daupdate.Update(rstPeople);
}
}
So, we send grid back to table.
We then send table back to database.
As you can see, this approach saves buckets of code.
the ONLY addtional issues here?
You are using a datapager. However, that means for each page navigation, re-bind the grid from that persisted table - do NOT re-load the data table from the database each time. But, a data pager complicates this VERY much, since on page navigation, we in theory would have to save the changes on that displayed page back to the table (we don't need to send table back to database, but we DO need to send possible changes from grid back to table. Thus, since navigation comes from that table, then this should work - and we not yet had to hit save to send persisted table back to database.
And note that the gridrow (and most controls) can return either the current page index or the overall index location of the row. So, I not done above with a datapager, but it should be possible to work.
And no real need for a edit button - I mean, what would edit do anyway? I don't think it is required - and just messes up the simple UI anyway.
And of course we should provide a cancel/undo. And all that would do is call LoadGrid again, and re-load grid from the database.
The above approaches should work with radGrid - but I never used it.
As noted, above idea works with GridView, listview and even older datagrid.
My preferred choice out of the 3 is actually list view, since as noted, you don't have to put messy template tags around each plain jane asp.net controls (such as text box, or as per above also a check box).
and the add row code in above, to allow adding a new row?
we have this:
protected void cmdAdd_Click(object sender, EventArgs e)
{
// add a new row to the grid
DataRow OneRow = rstPeople.Rows.Add();
GridView1.DataSource = rstPeople;
GridView1.DataBind();
}
Once again - really simple!!! and again it was easy since we operate against the table, and then just re-bind against the grid.

Accessing Header Text property of GridView TemplateField in the Code Behind when it is set from Header Template

I have a GridView in an asp .net application, where the Header Text of a template field is set in the Header Template of the field, as a label (where it will come from the resource file). Below is the code
<asp:GridView ID="gridView" ClientIDMode="Static" runat="server" AutoGenerateColumns="False" meta:resourcekey="grdViewResource">
<Columns>
<asp:TemplateField meta:resourcekey="TemplateFieldResource1">
<HeaderTemplate>
<asp:Label ID="lblNameHeader" Text="Name" runat="server" meta:resourcekey="lblNameHeaderResource1"/>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblNameValue" Text='<%# Eval("Name") %>'/>
</ItemTemplate>
</Columns>
</asp:GridView>
In code behind I am trying to access the HeaderText set on the column like this
var headerText = gridView.Columns[0].HeaderText;
But the value is coming Empty and I am not able to retrieve it from the gridView.Columns' HeaderTemplate property as well.
Please help me.
You have several problems with your code.
You are missing a closing </asp:TemplateField>. Your asp:Label is missing a runat="server" attribute.
If you want to use the .HeaderText property, this should be your markup:
<asp:GridView ID="gridView" ClientIDMode="Static" runat="server" AutoGenerateColumns="False" meta:resourcekey="grdViewResource">
<Columns>
<asp:TemplateField meta:resourcekey="TemplateFieldResource1" HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblNameValue" Text='<%# Eval("Name") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
If you want to use a HeaderTemplate with custom markup in it, then you need to cast the column to a TemplateField, then access the controls within it.

How to populate itemTemplates of TemplateField in gridview from datatable?

The table I am querying from has 3 fields, all varchar, but 2 of them are base64String from image and video files. I have added a gridview such:-
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<img id="image" runat="server" />
</ItemTemplate>
<ItemTemplate>
<a id="downloadLink" runat="server"></a>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I searched a lot but have no clue on how to populate the Template field column from a dataTable. I need to set the src attribute of the from database query and also need to set innerHTML for the link.
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<img src='<%#Eval("image_source")%>' runat="server" />
<a id="downloadLink" runat="server"><%#Eval("anchor_content")%></a>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Where image_source and anchor_content are assumed to be the columns returned by your SQL query.

How to fix the width for each column in GridView?

How can I fix the width for each column in GridView. My GridView keeps extend along with data in the cell. I need it to skip to new line when it reach the right side of the cell. This is my code in .aspx file:
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False" DataKeyNames="Emp_ID" DataSourceID="LinqDataSource1"
AllowPaging="True" AllowSorting="True" Width="900px" HorizontalAlign="Center" >
<Columns>
<asp:BoundField DataField="Emp_ID" HeaderText="ID"
InsertVisible="False" ReadOnly="True" SortExpression="Emp_ID"/>
<asp:BoundField DataField="Emp_Username"
HeaderText="Username" SortExpression="Emp_Username" />
<asp:BoundField DataField="Emp_Password"
HeaderText="Password" SortExpression="Emp_Password" />
<asp:BoundField DataField="Emp_Name"
HeaderText="ชื่อพนักงาน" SortExpression="Emp_Name" />
<asp:BoundField DataField="Emp_Address"
HeaderText="ที่อยู่" SortExpression="Emp_Address" />
<asp:BoundField DataField="Emp_Tel"
HeaderText="เบอร์โทรศัพท์" SortExpression="Emp_Tel" />
<asp:TemplateField HeaderText="รูปพนักงาน" SortExpression="Emp_Picture">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Emp_Picture") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Image ID="Image2" runat="server" Height="70px"
ImageUrl='<%# Eval("Emp_Picture", "{0}") %>' Width="50px" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Status" HeaderText="สถานะ"
SortExpression="Status" />
<asp:HyperLinkField DataNavigateUrlFields="Emp_ID"
DataNavigateUrlFormatString="AdminUpdate.aspx?Emp_ID={0}" Text="Edit" />
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="ChkSelectAll" runat="server"
AutoPostBack="True" oncheckedchanged="ChkSelectAll_CheckedChanged" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="Chk" runat="server" AutoPostBack="True" oncheckedchanged="Chk_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Here's my design view:
As you can see, the first 4 columns has no problem with that until column 5. It keeps extend cause all GridView extend out of the page
Set itemstyle width of every column.For example.
<asp:BoundField DataField="Emp_Address"
HeaderText="ที่อยู่" SortExpression="Emp_Address">
<ItemStyle Width="200px" HorizontalAlign="Left" />
</asp:BoundField>
Wrapping is done based on words so that any single word is not broken in two lines.
So won't work for you if your data has long string without space.
The problem is that you can't insert spaces on your own because that may change the meaning of data.
While showing in grid we show only that long string which can be accommodated in column and then add "..." (only if string is more than what is showing) and then add a tooltip to show the full string.
That way the grid formatting is not compromised and if user wants he can hover his mouse and see the whole string.
hope this helps Example
Try setting the property RowStyle-Wrap of the GridView to True.
You can use ItemStyle-Width to fix the column width ,but in case you enter characters which can not be enclosed in given width (As seen in your image) ,column will expand as per the inputs so you can use RowStyle-Wrap property of gridview
<asp:GridView ID="grdVwtrial" runat="server" RowStyle-Wrap="true">
RowStyle-Wrap==true should work I guess. For more clarifications refer this:
http://forums.asp.net/t/1263769.aspx

GridView Sorting is not working

Merged with GridView sorting works once only.
Please help me, I set Allowsorting="true" but sorting is not working in my GridView. I want automatic sorting i.e. sorting without handling its event.
Here is code of aspx page:
<asp:GridView ID="gdvSignatureLines" runat="server" CssClass="Grid1" AutoGenerateColumns="False"
SkinID="PagedGridView" AllowPaging="True" AllowSorting="True" DataKeyNames="Id"
onrowcommand="gdvSignatureLines_RowCommand"
onrowdeleting="gdvSignatureLines_RowDeleting"
onrowediting="gdvSignatureLines_RowEditing">
<PagerStyle CssClass="gridPager" HorizontalAlign="Right" />
<Columns>
<ucc:commandfieldcontrol headertext="Actions" showdeletebutton="true" buttontype="Image"
deleteimageurl="~/App_Themes/Default/images/delete.png" showeditbutton="true"
editimageurl="~/App_Themes/Default/images/edit.png" deleteconfirmationtext="Are you sure you want to delete?">
<ItemStyle HorizontalAlign="Center" Width="60px" />
</ucc:commandfieldcontrol>
<asp:BoundField DataField="SortOrder" HeaderText="Line" SortExpression="SortOrder" />
<asp:TemplateField HeaderText="Type">
<ItemTemplate>
<asp:Label ID="lblglTypeId" runat="server" Text='<%# Eval("GeneralLookup.LookupItem") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Label">
<ItemTemplate>
<asp:Label ID="lblglLabelId" runat="server" Text='<%# Eval("GeneralLookup1.LookupItem") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Caption" HeaderText="Caption" SortExpression="Caption" />
</Columns>
<EmptyDataTemplate>
<div class="divEmptyListingGrid">
--- No Signature Line Exists ---
</div>
</EmptyDataTemplate>
</asp:GridView>
Here is the code of CS file:
protected void LoadSignatureList(int reportId, string reportName)
{
lblHeading.Text = "Signature Line for " + reportName;
ReportOptionsBO reportOptionsBO = new ReportOptionsBO();
this.gdvSignatureLines.DataSource = reportOptionsBO.GetReportSignatureLineByReportId(reportId);
this.gdvSignatureLines.DataBind();
}
When I click on the Header of column "Line" or "Caption", nothing happens.
I have one more grid that is working fine. The difference between both is, data is bound to this grid on runtime. But the other grid's datasource is preset.
My current grid has not these options of Enable Paging and Enable Sorting.
Please help as soon as possible.

Categories

Resources