I want to add a column to my gridview while page is uploading.
My gridview takes his data from SQL static tables... and I want to add a column which contains the number of the row (1,2,3...)
Part of my gridview:
<asp:GridView ID="GridView1" runat="server" HorizontalAlign="Center"
AutoGenerateColumns="False" DataKeyNames="InjuryScenario_id"
DataSourceID="SqlDataSource30"
OnSelectedIndexChanged="GridView1_OnSelectedIndex" ShowHeaderWhenEmpty="True"
CellPadding="3" GridLines="None" BackColor="White" BorderColor="White"
BorderStyle="Ridge" BorderWidth="2px" CellSpacing="1">
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:BoundField DataField="InjuryScenario_id" HeaderText="מספר תרחיש" ReadOnly="True" SortExpression="InjuryScenario_id" />
<asp:BoundField DataField="Cause_name" HeaderText="מנגנון" SortExpression="Cause_name" />
<asp:BoundField DataField="City_name" HeaderText="יישוב" SortExpression="City_name" />
<asp:BoundField DataField="Place_name" HeaderText="מקום" SortExpression="Place_name" />
<asp:BoundField DataField="InjuryDay" HeaderText="יום" SortExpression="InjuryDay" Visible="False"/>
<asp:BoundField DataField="InjuryMonth" HeaderText="חודש" SortExpression="InjuryMonth" Visible="False"/>
<asp:BoundField DataField="InjuryYear" HeaderText="שנה" SortExpression="InjuryYear" Visible="False"/>
<asp:TemplateField HeaderText="תאריך">
<ItemTemplate>
<asp:Label ID="Label1" runat="server"><%#(int)Eval("InjuryDay")+"/"+ Eval("InjuryMonth")+"/"+ Eval("InjuryYear") %></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I've tried to use this method:
protected void Btn_AddCol_Click(object sender, EventArgs e)
{
TemplateField tf = new TemplateField();
tf.HeaderTemplate = new GridViewLabelTemplate(DataControlRowType.Header, "Col1", "Int32");
tf.ItemTemplate = new GridViewLabelTemplate(DataControlRowType.DataRow, "Col1", "Int32");
GridView1.Columns.Add(tf);
}
Thanks
Related
I´m trying to play around ItemStyle- Width and but this only works if i use Attribites.Add("Style"...) in my page load.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
...
}
gwActivity.Attributes.Add("style", "word-break:break-all;word-wrap:break-word");
}
However this is not a problem. My issue is that the column headers are affected in the ItemStyle-Width:... and i do NOT want that to be the case. Can i only play around with the rows and not the headers?
<%--************************ Gridview section ************************--%>
<asp:GridView ID="gwActivity" runat="server" AutoGenerateColumns="False" OnRowCommand="gwActivity_RowCommand" CssClass="gwActivity" >
<Columns>
<asp:BoundField DataField="ActivityID" HeaderText="ActivitID"></asp:BoundField>
</Columns>
<HeaderStyle BackColor="#E6E6E6" Font-Bold="false" Font-Names="Arial" ForeColor="#000000" />
<%-- <AlternatingRowStyle BackColor="#E6E6E6" /> --%>
</asp:GridView>
try this..
<asp:GridView ID="gwActivity" runat="server"
AutoGenerateColumns="False" OnRowCommand="gwActivity_RowCommand"
CssClass="gwActivity" >
<HeaderStyle BackColor="#E6E6E6" Font-Bold="false" ForeColor="#000000" Font-Names="Arial />
<Columns>
<asp:BoundField DataField="ActivityID" HeaderText="ActivitID"></asp:BoundField>
<asp:BoundField DataField="ActivityID" HeaderText="ActivitID" HeaderStyle-Font-Bold="false"
HeaderStyle-Font-Size="12px" ItemStyle-HorizontalAlign="Left" ItemStyle-Width="25">
<HeaderStyle Font-Bold="False" Font-Size="12px" />
<ItemStyle Font-Size="12px" HorizontalAlign="Left" Width="200px" /> //set width you want..
</asp:BoundField>
</Columns>
</asp:GridView>
I have an <asp:ButtonField> inside a gridview. How do I target the button in the gridview to make it Visible on runtime based on a condition ? I am not able to target it since it doesnt have the ID property. I am stuck here. Here is the code below
<asp:GridView ID="OrdersDataList1" runat="server" DataKeyNames="OrderID" Width="100%" SkinID="Gridview" OnPageIndexChanging="orders_PageIndexChanging"
EmptyDataText="You have no orders." AllowSorting="True" OnSorting="OnSort" AllowPaging="true" PageSize="15" AutoGenerateColumns="False" OnRowCommand="updateStatus">
<Columns>
<asp:BoundField DataField="CustomerUser_ID" HeaderText="UserID" Visible="true" />
<asp:BoundField DataField="OrderID" HeaderText="OrderNo" InsertVisible="False" ReadOnly="True" HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="Left" SortExpression="OrderID" />
<asp:BoundField DataField="OrderDate" HeaderText="OrderDate" SortExpression="OrderDate" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center"/>
<asp:BoundField DataField="Base" HeaderText="Base" DataFormatString="{0:C}" SortExpression="Base" HeaderStyle-HorizontalAlign="Right" ItemStyle-HorizontalAlign="Right"/>
<asp:BoundField DataField="Freight" HeaderText="Freight" DataFormatString="{0:C}" SortExpression="Freight" HeaderStyle-HorizontalAlign="Right" ItemStyle-HorizontalAlign="Right"/>
<asp:BoundField DataField="Total" HeaderText="Total" DataFormatString="{0:C}" SortExpression="Total" HeaderStyle-HorizontalAlign="Right" ItemStyle-HorizontalAlign="Right"/>
<asp:BoundField DataField="Products" HeaderText="Products" SortExpression="Products" DataFormatString="{0} product" HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="Left"/>
<asp:BoundField DataField="Units" HeaderText="Units" SortExpression="Units" DataFormatString="{0} units" HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="Left"/>
<asp:BoundField DataField="OrderStatusName" HeaderText="Current Status" SortExpression="OrderStatusName" HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="Left"/>
<asp:BoundField DataField="OrderStatusID" HeaderText="Orderstatusid" Visible="true" />
<asp:BoundField DataField="OrderTracking_ID" HeaderText="TrackingNo" SortExpression="OrderTracking_ID" HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="Left"/>
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<%# GetViewOrderLink(Eval("OrderID").ToString(), Eval("OrderState").ToString())%>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left" />
<ItemStyle HorizontalAlign="Left" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Change Status" SortExpression="OrderStatusName">
<ItemTemplate>
<asp:DropDownList ID="OrderStatusDD" runat="server"
DataSourceID="OrdersStatuses" DataTextField="OrderStatusName" DataValueField="OrderStatusID" Visible="false">
</asp:DropDownList>
<asp:SqlDataSource ID="OrdersStatuses" runat="server"
ConnectionString="<%$ ConnectionStrings:SqlConn %>"
SelectCommand="SELECT [OrderStatusID], [OrderStatusName] FROM [Orders_Statuses] where OrderStatusID = 2 or OrderStatusID = 8 ORDER BY [OrderStatusName]">
</asp:SqlDataSource>
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField ButtonType="Button" Text="Update status" Visible="false" HeaderText="Change Status" />
</Columns>
</asp:GridView>
PS I have the onrowCommand set on the gridview to listen to button click in gridview
You need to create RowCreated event for the gridview example
Before the GridView control can be rendered, a GridViewRow object must be created for each row in the control. The RowCreated event is raised when each row in the GridView control is created. This enables you to provide an event-handling method that performs a custom routine, such as adding custom content to a row, whenever this event occurs.
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
}
OR
<asp:GridView runat="server" ID="GV1" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Age" HeaderText="Age" />
<asp:TemplateField>
<ItemTemplate>
<asp:Button runat="server" Text="Reject"
Visible='<%# IsOverAgeLimit((Decimal)Eval("Age")) %>'
CommandName="Select"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected Boolean IsOverAgeLimit(Decimal Age) {
return Age > 35M;
}
Reference example
You can use the RowCreated event in the GridView as follows:
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
Button btn = (Button) e.Row.Cells[12].Controls[0];
if(1==1)
{
btn.Visible = true;
}
}
((BoundField)grv_selec.Columns[1]).DataFormatString = "{0:N2}";
MY grid view code
<asp:GridView ID="grdAccidentMaster" runat="server" AutoGenerateColumns="False"
Width="80%" BackColor="White" BorderColor="#DEDFDE" BorderStyle="Solid" BorderWidth="1px"
EmptyDataText="No Records found" CellPadding="4" ForeColor="Black" GridLines="Both"
DataKeyNames="IncidentNo" OnRowDataBound="grdAccidentMaster_RowDataBound">
<Columns>
<asp:BoundField DataField="IncidentNo" HeaderText="IncidentNo" />
<asp:BoundField DataField="CreatedDate" HeaderText="Created Date" />
<asp:BoundField DataField="AccidentDate" HeaderText="Accident Date" />
<asp:BoundField DataField="PoliceStation" HeaderText="Police Station" />
<asp:BoundField DataField="City" HeaderText="City Name" />
<asp:BoundField DataField="RoadCondition" HeaderText="Road Condition" />
<asp:BoundField DataField="RoadFeature" HeaderText="Road Feature" />
<asp:TemplateField HeaderText="Print">
<ItemTemplate>
<asp:Button runat="server" Text="Click" ID="btnClick" OnClick="btnPrint_click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
MY grid view Output
If i click the Click button under Print column. I need to get the IncidentNo value '4022' on onclick function.
Add an event in Gridview :
OnRowCommand="grdAccidentMaster_OnRowCommand"
Change template for button :
<ItemTemplate>
<asp:Button runat="server" Text="Click" ID="btnClick"
CommandName="SendIncidentNo" CommandArgument='<%# Eval("IncidentNo") %>' />
</ItemTemplate>
Code behind :
protected void grdAccidentMaster_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName != "SendIncidentNo") return;
int incidentNo = Convert.ToInt32(e.CommandArgument);
// do something
}
This might get a little confusing but I will try my best to explain and would appreciate any help.I have a gridview like
<asp:GridView ID="GridView1" runat="server" Width="936px" AllowPaging="True" AutoGenerateColumns="False" CellPadding="3" DataSourceID="SqlDataSource1" OnRowCommand="GridView1_RowCommand" style="text-align: center" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellSpacing="2" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField="TaskId" HeaderText="TaskId" InsertVisible="False" ReadOnly="True" SortExpression="TaskId" />
<asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
<asp:BoundField DataField="Body" HeaderText="Body" SortExpression="Body" Visible="false" />
<asp:BoundField DataField="Reward" HeaderText="Reward(Rs)" SortExpression="Reward" />
<asp:BoundField DataField="TimeAllotted" HeaderText="Time(Min)" SortExpression="TimeAllotted" />
<asp:BoundField DataField="PosterName" HeaderText="Uploader" SortExpression="PosterName" />
<asp:ButtonField ButtonType="Button" CommandName="Select" Text="Perform Task" ControlStyle-ForeColor="White" ControlStyle-Font-Bold="true">
<ControlStyle BackColor="#CC6600" Font-Bold="True" ForeColor="White"></ControlStyle>
</asp:ButtonField>
</Columns>
When I click on the buttonfield of a particular row, I get directed to a new page which asks me to perform some task.
I want to disable the 'perform task' buttonfield for that particular user whenever a task is performed.
How can I do that?
Try this code:
<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound" ...>
Other settings
</asp:GridView>
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
var button = (Button) e.Row.Cells[e.Row.Cells.Count - 1].Controls[0];
button.Enabled = CanCurrentUserViewButton();
}
}
private bool CanCurrentUserViewButton()
{
//Logic...
}
i'm using a GridView and trying to sort and page it.
I have more than 20 rows on my DataBase, but the GridView just shows 10.
I set AllowPaging=true but noting happened.
Also I'm using AllowSorting = true and OnSorting="GridView_Sorting". But when I click on the header to sort the the content of that column, it does not enters on my OnSorting="GridView_Sorting" it goes right to the GridView1_RowCommand why ?
Sometimes it just give me this error:
Object reference not set to an instance of an object error
Here's my Code:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" style="font-family: Verdana, Arial, Sans-Serif;"
CssClass="gridview" OnSorting="GridView_Sorting"
AllowSorting ="True" AllowPaging="True" BackColor="#CCCCCC"
BorderStyle="Inset" BorderWidth="2px" BorderColor="GrayText"
CellPadding="1"
CellSpacing="5"
HeaderStyle-HorizontalAlign="Center"
OnRowDataBound="GridView1_RowDataBound"
ForeColor = "Black" RowStyle-CssClass="gridview"
OnRowCommand="GridView1_RowCommand">
<AlternatingRowStyle BackColor="#CCCCCC" />
<columns>
<asp:BoundField HeaderText="ID" DataField="id" SortExpression="id" />
<asp:BoundField HeaderText="PRIORIDADE" DataField="prioridade" ItemStyle-HorizontalAlign="Center" SortExpression="prioridade" SortExpression="prioridade" />
<asp:BoundField HeaderText="SITUAÇÃO" DataField="situacao" ItemStyle-HorizontalAlign="Center" >
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField HeaderText="RESPONSAVEL" DataField="responsavel" HeaderStyle-Width="65px" ItemStyle-HorizontalAlign="Center">
<HeaderStyle Width="65px" />
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField HeaderText="DATA DE CADASTRO" DataField="dt_cadastro" SortExpression="dt_cadastro" DataFormatString="{0:dd/MM/yyyy}" HeaderStyle-Width="60px"ItemStyleHorizontalAlign="Center" >
<HeaderStyle Width="60px" />
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField HeaderText="PREVISÃO DE TÉRMINO" DataField="previsao_termino" DataFormatString="{0:dd/MM/yyyy}" HeaderStyle-Width="60px"
ItemStyle-HorizontalAlign="Center">
<HeaderStyle Width="60px" />
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField HeaderText="PROJETO" DataField="projeto" ItemStyle-HorizontalAlign="Center"></asp:BoundField>
<asp:BoundField HeaderText="FUNCIONALIDADE" DataField="funcionalidade" ItemStyle-HorizontalAlign="Center" />
<asp:BoundField HeaderText="CLUBE" DataField="clube" ItemStyle-HorizontalAlign="Center" />
<asp:TemplateField HeaderStyle-Width="70px" HeaderText="VISUALIZAR" >
<ItemTemplate>
<asp:Button ID="Btn_Visualizar" runat="server" Text="VISUALIZAR" CssClass="Btn_Grid" Font-Size="7pt" Font-Names="Verdana, Arial" OnClick="Btn_Visualizar_Click"CommandName="visualizar" CommandArgument="<%# ((GridViewRow)Container).RowIndex %>" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="66px" HeaderText="ALTERAR">
<ItemTemplate>
<asp:Button ID="Btn_Alterar" runat="server" Text="ALTERAR" CssClass="Btn_Grid" Font-Size="7pt" Font-Names="Verdana, Arial"CommandName="editar" CommandArgument="<%# ((GridViewRow)Container).RowIndex %>" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="66px" HeaderText="FEEDBACK">
<ItemTemplate>
<asp:Button ID="Btn_Feedback" runat="server" Text="ADICIONAR" CssClass="Btn_Grid" Font-Size="7pt" Font-Names="Verdana,Arial"CommandName="feedback" CommandArgument="<%# ((GridViewRow)Container).RowIndex %>" />
</ItemTemplate>
</asp:TemplateField>
</columns>
My CodeBehind:
protected void GridView_Sorting(object sender, GridViewSortEventArgs e)
{
string[] strSortExpression = ViewState["SortExpression"].ToString().Split(' ');
// If the sorting column is the same as the previous one,
// then change the sort order.
if (strSortExpression[0] == e.SortExpression)
{
if (strSortExpression[1] == "ASC")
{
ViewState["SortExpression"] = e.SortExpression + " " + "DESC";
}
else
{
ViewState["SortExpression"] = e.SortExpression + " " + "ASC";
}
}
// If sorting column is another column,
// then specify the sort order to "Ascending".
else
{
ViewState["SortExpression"] = e.SortExpression + " " + "ASC";
}
// Rebind the GridView control to show sorted data.
GridView1.DataSource = ch.BuscaTodosChamados();
GridView1.DataBind();
}
Add SortExpression attribute for each sortable column, informing its DataField.