How to display Checkbox in asp.net webform Gridview - c#

I want to show Checkbox in Gridview,
But now, it only show dynamic data in Gridview,
Didn't show dynamic checkbox in Gridview.
How can I fix problem, thanks.
.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
using (var conn = new SqlConnection(strConn))
{
try
{
conn.Open();
ckloginConnectionString.SelectCommand = #"select a,b,c,d ,e from testTable where a =#a ";
ckloginConnectionString.SelectParameters.Add("a", a);
//==================
DataView dv = (DataView)ckloginConnectionString.Select(new DataSourceSelectArguments());
GridView1.DataSource = dv;
GridView1.DataBind();
//==================
ckloginConnectionString.DataBind();
ckloginConnectionString.DataBind();
}
catch (Exception ex)
{
ex.ToString();
}
}
}
.aspx
<div class="table-wrapper">
<asp:GridView runat="server" ID="GridView1" CssClass="alt" DataKeyNames="InsertedDate,Upload_Schoo_No" AutoGenerateColumns="False" OnRowCommand="grvclscour_RowCommand">
<Columns>
<asp:TemplateField HeaderText="check" InsertVisible="false" ItemStyle-BorderStyle="Double">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" Visible="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="a" HeaderText="a">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="b" HeaderText="b">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="c" HeaderText="c">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:ButtonField CommandName="d" HeaderText="d">
<ItemStyle HorizontalAlign="Center" />
</asp:ButtonField>
<asp:ButtonField CommandName="e" HeaderText="e">
<ItemStyle HorizontalAlign="Center" />
</asp:ButtonField>
</Columns>
</asp:GridView>
</div>

Eval would do what you want i guess.
change your grid desing like this:
<asp:GridView runat="server" ID="GridView1" CssClass="alt" DataKeyNames="InsertedDate,Upload_Schoo_No" AutoGenerateColumns="False" OnRowCommand="grvclscour_RowCommand">
<Columns>
<asp:TemplateField HeaderText="check" InsertVisible="false" ItemStyle-BorderStyle="Double">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" Visible="true" Checked='<%# Eval("YourDataField") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="a" HeaderText="a">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="b" HeaderText="b">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="c" HeaderText="c">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:ButtonField CommandName="d" HeaderText="d">
<ItemStyle HorizontalAlign="Center" />
</asp:ButtonField>
<asp:ButtonField CommandName="e" HeaderText="e">
<ItemStyle HorizontalAlign="Center" />
</asp:ButtonField>
</Columns>
</asp:GridView>

Related

ASP, DropDownList grid view

I'm new to ASP MVC. I want to load data from a database in DropDownList into a gridview. But DATA cannot load.
HTML CODE
<asp:BoundField DataField="id" HeaderText="Code">
<HeaderStyle Width="106px" HorizontalAlign="center" BorderColor="White" BorderWidth="1" />
<ItemStyle Width="102px" HorizontalAlign="center" BorderWidth="1px" />
</asp:BoundField>
<asp:BoundField DataField="name" HeaderText="Nom Cours">
<HeaderStyle Width="300px" HorizontalAlign="left" BorderColor="White" BorderWidth="1" />
<ItemStyle Width="300px" HorizontalAlign="left" BorderWidth="1px" />
</asp:BoundField>
<asp:templatefield HeaderText="Prix / Heure (HTG)">
<HeaderStyle Width="160px" HorizontalAlign="center" BorderColor="White" BorderWidth="1" />
<ItemStyle Width="160px" HorizontalAlign="center" BorderWidth="1px" />
<itemtemplate>
<asp:DropDownList ID="ddlprice" Width="160px" HorizontalAlign="center" runat="server">
</asp:DropDownList>
</itemtemplate>
</asp:templatefield>
<asp:templatefield HeaderText="SĂ©lectionner">
<HeaderStyle Width="300px" HorizontalAlign="center" BorderColor="White" BorderWidth="1" />
<ItemStyle Width="300px" HorizontalAlign="center" BorderWidth="1px" />
<itemtemplate>
<asp:checkbox ID="cbSelect" CssClass="gridCB" runat="server" HorizontalAlign="center"></asp:checkbox>
</itemtemplate>
</asp:templatefield>
</Columns>
<FooterStyle BackColor="Tan" Height="30px" HorizontalAlign="Center" />
<HeaderStyle BackColor="Navy" Font-Bold="True" Height="22px" HorizontalAlign="Left"
ForeColor="WhiteSmoke" BorderColor="Navy" VerticalAlign="Top" BorderWidth="2px" Width="910px" Font-Size="Small" />
<PagerSettings Mode="NumericFirstLast" />
<PagerStyle BackColor="SkyBlue" ForeColor="WhiteSmoke"
HorizontalAlign="Center" />
<RowStyle Height="5px" Font-Size="Smaller" />
<SelectedRowStyle BackColor="Aquamarine" ForeColor="GhostWhite" BorderColor="Silver"
BorderStyle="None" />
<SortedAscendingCellStyle BackColor="SkyBlue" />
<SortedAscendingHeaderStyle BackColor="#DAC09E" />
<SortedDescendingCellStyle BackColor="#E1DB9C" />
<SortedDescendingHeaderStyle BackColor="#C2A47B" />
</asp:GridView>
</div>
C# CODE
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ddlClassroom.SelectedValue = "-1";
BindDataGridClass();
BindDataGridCourse();
loadListPrice();
}
private void loadListPrice()
{
List<Course> listPrice = Course.getListCoursePriceOrdered();
ddlprice.DataValueField = "id";
ddlprice.DataTextField = "price";
ddlprice.DataSource = listPrice;
ddlprice.DataBind();
//ddlprice.Items.Insert(0, new DropDownListItem("--Selectionner--", "-1"));
ddlprice.SelectedValue = "0";
}
First add the OnRowDataBound event to the GridView
<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound">
Then in code behind
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//check if the row is a datarow
if (e.Row.RowType == DataControlRowType.DataRow)
{
//find the dropdownlist in the row with findcontrol and cast it back to one
DropDownList ddlprice = e.Row.FindControl("ddlprice") as DropDownList;
//you now have access to all the dropdownlist properties
ddlprice.DataSource = Course.getListCoursePriceOrdered();
ddlprice.DataValueField = "id";
ddlprice.DataTextField = "price";
ddlprice.DataBind();
ddlprice.SelectedValue = "0";
}
}

hyperlink in grid view not populating values in another page when clicked

please help with this hyperlink thing.. i got a grid view where one of the column contains hyperlink say ViewDetails. upon clicking ViewDetails it should get navigate to another page called as Reports.aspx where the page should display the grid row value of selectd column in grid view in labels. i have used row data bound event .. im getting blank labels if i click the hyperlink . i have written stored procedure to get the row values. and im calling it through KEY.. its TaskID which is an auto generated column which is invisible. depending on the key value i need to display the row values.
here are the codes
<asp:GridView ID="GrdViewMyTasks" runat="server" AllowSorting="True"
AutoGenerateColumns="False" BackColor="White" BorderColor="#0061C1"
BorderStyle="None" CaptionAlign="Bottom" EmptyDataText="No Records Found"
Font-Names="Verdana" Font-Size="X-Small" ForeColor="#0061C1"
Height="179px" OnRowDataBound="GrdViewMyTasks_RowDataBound"
ShowFooter="True" ShowHeaderWhenEmpty="True" Width="99%"
onselectedindexchanged="GrdViewMyTasks_SelectedIndexChanged"
OnRowCreated="GrdViewMyTasks_RowCreated" >
<Columns>
<asp:BoundField DataField="TaskID" HeaderText="SL No" Visible="False" ReadOnly="True">
<FooterStyle BackColor="#0061C1" />
<HeaderStyle BackColor="#0061C1" HorizontalAlign="Center" VerticalAlign="Middle" />
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:BoundField>
<asp:TemplateField HeaderText="Task Name">
<ItemTemplate>
<asp:Label ID="TaskName" runat="server"
Font-Names="Verdana" Font-Size="X-Small" Height="24px"
Text='<%# Eval("TaskName")%>' Width="70px"></asp:Label>
</ItemTemplate>
<FooterStyle BackColor="#0061C1" />
<HeaderStyle BackColor="#0061C1" ForeColor="White" />
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Due Date">
<ItemTemplate>
<asp:Label ID="DueDate" runat="server" Font-Names="Verdana" Font-Size="X-Small"
Height="20px" Width="70px" Text='<%# Eval("DueDate","{0:dd/MM/yyyy}")%>' DataFormatString="{0:dd/MM/yyyy}"></asp:Label>
</ItemTemplate>
<FooterStyle BackColor="#0061C1" />
<HeaderStyle BackColor="#0061C1" ForeColor="White" />
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:Label ID="Description" runat="server" Font-Names="Verdana" Font-Size="X-Small" Height="20px" Width="90px" Text='<%# Eval("Description")%>'></asp:Label>
</ItemTemplate>
<FooterStyle BackColor="#0061C1" />
<HeaderStyle BackColor="#0061C1" ForeColor="White" />
<ItemStyle HorizontalAlign="Left" VerticalAlign="Middle" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Assign By">
<ItemTemplate>
<asp:Label ID="AssignBy" runat="server" Font-Names="Verdana" Font-Size="X-Small" Height="20px" Width="90px" Text='<%# Eval("AssignBy")%>'></asp:Label>
</ItemTemplate>
<FooterStyle BackColor="#0061C1" />
<HeaderStyle BackColor="#0061C1" ForeColor="White" />
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:Label ID="Status" runat="server" Font-Names="Verdana" Font-Size="X-Small" Height="20px" Width="90px" Text='<%# Eval("Status")%>'></asp:Label>
</ItemTemplate>
<FooterStyle BackColor="#0061C1" />
<HeaderStyle BackColor="#0061C1" ForeColor="White" />
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:TemplateField>
<asp:TemplateField HeaderText="% Complete">
<ItemTemplate>
<asp:Label ID="PercentageComplete" runat="server" Font-Names="Verdana" Font-Size="X-Small" Height="20px" Width="50px" Text='<%# Eval("PercentageComplete")%>'></asp:Label>
</ItemTemplate>
<FooterStyle BackColor="#0061C1" />
<HeaderStyle BackColor="#0061C1" ForeColor="White" />
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:TemplateField>
<asp:TemplateField HeaderText="View Details">
<ItemTemplate>
<asp:HyperLink ID="ViewDetails" runat="server" Font-Names="Verdana" Font-Size="X-Small" Height="24px" Width="70px" ForeColor="#0061C1" Text="ViewDetails" NavigateUrl="Reports.aspx">View</asp:HyperLink>
</ItemTemplate>
<FooterStyle BackColor="#0061C1" />
<HeaderStyle BackColor="#0061C1" ForeColor="White" />
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:TemplateField>
</Columns>
</asp:GridView>
aspx.cs code
protected void GrdViewMyTasks_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink ViewDetails = e.Row.FindControl("ViewDetails") as HyperLink;
ViewDetails.NavigateUrl = "Reports.aspx?TaskID=" + e.Row.Cells[0].Text;
}
}
code in reports.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
MTMSService obj = new MTMSService();
DBAccess db = new DBAccess();
{
MTMSDTO objc = new MTMSDTO();
{
//objc.TaskID = Convert.ToInt32(Request.QueryString["TaskID"]);//
DataSet rep = obj.GetReports();
DataView Rprts = new DataView();
Rprts.Table = rep.Tables[0];
var table = rep.Tables[0];
if (table.Rows.Count > 0)
{
LblTaskID.Text = rep.Tables[0].Rows[0]["TaskID"].ToString();
LblTaskName.Text = rep.Tables[0].Rows[0]["TaskName"].ToString();
LblDueDate.Text = rep.Tables[0].Rows[0]["DueDate"].ToString();
LblDescription.Text = rep.Tables[0].Rows[0]["Description"].ToString();
LblAssignBy.Text = rep.Tables[0].Rows[0]["AssignBy"].ToString();
LblStatus.Text = rep.Tables[0].Rows[0]["Status"].ToString();
LblPercentageComplete.Text = rep.Tables[0].Rows[0]["PercentageComplete"].ToString();
}
else
{
}
LblTaskName.Visible = true;
LblAssignBy.Visible = true;
LblDescription.Visible = true;
LblDueDate.Visible = true;
LblStatus.Visible = true;
LblPercentageComplete.Visible = true;
LblAssignTo.Visible = false;
}
}
}
and this is my stored procedure
ALTER PROCEDURE [dbo].[GetReports]
#TaskID int
AS
Select TaskName, DueDate, Description, AssignBy, Status, PercentageComplete, TaskID
From dbo.Task
Where TaskID = #TaskID;
please let me know where im goin wrong. im unable to get the perfect solution for this from past 1 week... its getting headache thing ..
getting error "input string is not in correct format" at commented line of reports.cs file
You're querying the database with Session["TaskId"] and you're showing task id on UI from query string. Are you sure that both are same?
I think you might want to use taks id from query string rather than session.
objc.TaskID = Convert.ToInt32(Request.QueryString["TaskID"]);
Update -
Filter the table based on your query string
rep.Tables[0].Select(string.Format("TaskID={0}", Request.QueryString["TaskID"]));

GridView allowPaging= true not showing page numbers 2 and 3. Shows 14567

i have a gridview that I need to have paged. When I allowPaging=true, It shows 145678910.... It won't show pages 2 and 3. If I try to change the Mode to NextPreviousFirstLast, It only shows 'Next' on the first page, and if I click that, it only shows 'First' and 'Last' on the second page. Here is the code:
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="Black" AutoGenerateColumns="False" BackColor="#CCCCCC"
BorderColor="#666666" OnRowDataBound = "HandleRowDataBound" BorderStyle="Solid" BorderWidth="1px" CellSpacing="2" Width ="942px"
Font-Names="Arial" Font-Size="8pt" ShowHeaderWhenEmpty="True" CSSClass="mytable" AllowPaging="true" OnPageIndexChanging="GridView1_PageIndexChanging"
PageSize="25">
<PagerSettings Mode="NextPreviousFirstLast" FirstPageText="First" PreviousPageText="Previous" NextPageText="Next" LastPageText="Last" />
<Columns>
<asp:TemplateField HeaderText="Select" ControlStyle-Width = "30px">
<ItemTemplate>
<asp:CheckBox runat="server" ID="DiscontinuedCheckBox" CssClass="SelectCheckBox" />
</ItemTemplate>
<ControlStyle Width="30px"></ControlStyle>
<ItemStyle Wrap="False" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Recall Qty" ItemStyle-Wrap="true" ItemStyle-Width="100px" >
<ItemTemplate >
<img id="star1" runat ="server" src="../Images/red_star.gif" alt="Red Star" class="RedStars"/>
<asp:TextBox runat ="server" ID="textBoxQty" Width = "50px" Text ="1" ReadOnly="false" />
</ItemTemplate>
<HeaderStyle Width = "100px" />
<ItemStyle Width="100px" />
<ItemStyle Wrap="False" Width="60px"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delivery Location" >
<ItemTemplate >
<div style="width:200px">
<div style ="float : left; ">
<asp:CheckBox runat="server" ID="packShipCB" Text ="Pack Ship or " CssClass="SendToShip" AutoPostBack="false" />
</div>
<asp:TextBox runat ="server" ID="deliveryLocationTB" CssClass="AllDelivery" ReadOnly ="false" Width="80px" />
</div>
</ItemTemplate>
<HeaderStyle Width = "200px" />
<ItemStyle Width="200px" />
<ItemStyle Width ="160px" />
</asp:TemplateField>
<%-- <asp:BoundField HeaderText="Data" />--%>
<asp:BoundField HeaderText="Request Number" DataField="requestNumber" ItemStyle-Width = "50px">
<HeaderStyle Wrap="True" Width="50px" />
<ItemStyle Wrap="True" Width="50px" />
</asp:BoundField>
<asp:BoundField HeaderText="Item Number" DataField="materialLineItemID" />
<asp:BoundField HeaderText="Program" DataField="programName" >
<ItemStyle Wrap="False" />
</asp:BoundField>
<asp:BoundField HeaderText="Program POC" DataField="programPOC" >
<ItemStyle Wrap="False" />
</asp:BoundField>
<asp:BoundField HeaderText="Material Number" DataField="materialNumber" ItemStyle-Width="100px">
<HeaderStyle Wrap="False" />
</asp:BoundField >
<asp:BoundField HeaderText="Qty in Storage" DataField="availableQty" ItemStyle-Width="100px">
<ItemStyle Width="100px" Wrap="False"></ItemStyle>
</asp:BoundField >
<asp:BoundField HeaderText="Description" DataField="Description" ItemStyle-Width="300px" >
<ItemStyle Width="300px" Wrap="False"></ItemStyle>
</asp:BoundField>
<asp:BoundField HeaderText="Serialized" DataField="Serialized" ItemStyle-Width="100px">
<ItemStyle Width="100px"></ItemStyle>
</asp:BoundField>
<asp:BoundField HeaderText="Serial Number" DataField="serialNumber" ItemStyle-Width="200px">
<ItemStyle Width="200px" Wrap="False"></ItemStyle>
</asp:BoundField>
<asp:BoundField HeaderText="Shelf Life" DataField="shelfLIfe" DataFormatString="{0:d}" HtmlEncode="false" ItemStyle-Width="100px" >
<ItemStyle Width="100px"></ItemStyle>
</asp:BoundField>
<asp:BoundField HeaderText="Cost Center" DataField="costCenter" ItemStyle-Width="200px">
<ItemStyle Width="200px" Wrap="False"></ItemStyle>
</asp:BoundField>
<asp:BoundField HeaderText="Charge Number" DataField="chargeNumber" ItemStyle-Width="200px">
<ItemStyle Width="200px" Wrap="False"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="contractNumber" HeaderText="Contract Number" ItemStyle-Width="200px">
<HeaderStyle Wrap="False" />
<ItemStyle Width="200px" />
</asp:BoundField>
<asp:BoundField DataField="assetTagNumber" HeaderText="Asset Tag Number" ItemStyle-Width="200px">
<HeaderStyle Wrap="False" />
<ItemStyle Width="200px" />
</asp:BoundField>
<asp:BoundField HeaderText="Storage Duration" DataField="Duration" ItemStyle-Width="200px">
<ItemStyle Width="200px" Wrap="False"></ItemStyle>
</asp:BoundField>
<asp:BoundField HeaderText="Handling Unit Number" DataField="handlingUnitNumber" ItemStyle-Width="100px">
<ItemStyle Width="100px" Wrap="False"></ItemStyle>
</asp:BoundField >
<asp:BoundField HeaderText="Storage Location" DataField="storageLocation" ItemStyle-Width="100px">
<ItemStyle Width="100px" Wrap="False"></ItemStyle>
</asp:BoundField >
<asp:BoundField HeaderText="Time in Storage" DataField="storageTime" ItemStyle-Width="200px">
<ItemStyle Width="200px" Wrap="False"></ItemStyle>
</asp:BoundField>
</Columns>
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="#999999" Font-Bold="True" ForeColor="#880C1B"
HorizontalAlign="Center" Font-Size="9pt" Wrap="true" BorderStyle="Solid" VerticalAlign="Middle"
BorderWidth="1px"/>
<PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" />
<RowStyle BackColor="White" HorizontalAlign="Center" CssClass="Unselected"
Wrap="false" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#808080" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#383838" />
</asp:GridView>
and here is the code behind:
protected void Page_Load(object sender, EventArgs e)
{
siteID = int.Parse(Request.QueryString["s"].ToString());
FillDetails();
}
//Pulls data from database for items to be recalled based on site, and user rights and enables to functions of the controls
private void FillDetails()
{
DataSet materials = RequestDB2.GetStoredMaterialsView(siteID);
GridView1.DataSource = materials;
GridView1.DataBind();
if (GridView1.Rows.Count >= 9)
paneling.Style["height"] = "300px";
//if not items exit
if (materials == null || materials.Tables[0].Rows.Count == 0)
{
Error.InnerText = "You have no materials to be recalled from this site.";
}
else
{
//Adds thead and tbody tags
GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
}
protected void HandleRowDataBound(object sender, GridViewRowEventArgs e)
{
}
Here is what I see:
WHen I look at firebug, I see that pages 2 and 3 have display:none. ANy thoughts on why this might be happening?
You are not assigning data source in GridView1_PageIndexChanging. You need to assigned datasource before binding. You better try calling FillDetails()
Change
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
}
To
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
FillDetails();
}
Try using PagerSetting as..
<PagerSettings FirstPageText="First Page" LastPageText="Last Page"
Mode="NumericFirstLast" Position="TopAndBottom" />
protected void grdView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.DataSource = RequestDB2.GetStoredMaterialsView(siteID);
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
}

Gridview, convert text cells to buttons in Code behind

I have a gridview, which have data from a SQL database. The database conaints jobs that a group need to work with. On my last column it says if it's finished or not. If its done, it will show a dateTime for when its finished, but if its not, the database contains 0 for this cell, and need a Button, that can make it finished, when it is.
Therefor the code first retrive data from the database, then i want to use RowDataBound to check if i need to show a Button, instead of the text from database. I also need an event for this button, so i can update the database with, an dateTime when finished.
Here's the code for my gridview:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="OverviewPlannedJobs" DataKeyNames="ID"
onrowcommand="Gridview1_RowCommand" onrowdatabound="GridView1_RowDataBound"
Width="631px">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID"
InsertVisible="False" ReadOnly="True">
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:BoundField>
<asp:BoundField DataField="week" HeaderText="Uke" SortExpression="week">
<HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" />
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:BoundField>
<asp:BoundField DataField="dayNumb" HeaderText="Dag"
SortExpression="dayNumb">
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:BoundField>
<asp:BoundField DataField="oven" HeaderText="Ovn"
SortExpression="oven">
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:BoundField>
<asp:BoundField DataField="section" HeaderText="Seksjon"
SortExpression="section">
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:BoundField>
<asp:BoundField DataField="pit" HeaderText="Pit" SortExpression="pit">
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:BoundField>
<asp:BoundField DataField="job" HeaderText="Jobb"
SortExpression="job">
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:BoundField>
<asp:BoundField DataField="priority" HeaderText="Prioritet"
SortExpression="priority">
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:BoundField>
<asp:BoundField DataField="timeEdited" HeaderText="Lagt til eller endret"
SortExpression="timeEdited" >
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:BoundField>
<asp:ButtonField ButtonType="Button" CommandName="editts" HeaderText="Valg"
Text="Rediger">
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:ButtonField>
<asp:ButtonField ButtonType="Button" CommandName="delete" Text="Slett">
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:ButtonField>
<asp:TemplateField HeaderText="Fullført?" SortExpression="finished">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("finished") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
then i have this rowdatabound function in code behind:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//Make button where finished equals zero
if (e.Row.Cells[11].Text.Equals("0"))
{
//insert button
}
}
I'm sorry, its not working for me. Can't figure out why, but get error at one of these
DataRow row = ((DataRowView)e.Row.DataItem).Row;
string value0 = row[3].ToString();
i don't have an own databinding method since i've used the configure datasource for the gridview.
Think i will try to make an button itemtemplate, and then change the text, or disable button depending on the database result.
Try this i have tested
Code Behind:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRow row = ((DataRowView)e.Row.DataItem).Row;
string value0 = row[3].ToString();
if (value0 == "0")
{
e.Row.Cells[2].Text = "";
Button btn=new Button();
btn.Text="finish";
e.Row.Cells[2].Controls.Add(btn);
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
gvBind();
}
public void gvBind()
{
SqlDataAdapter dap=new SqlDataAdapter("select id,name,job,status from myTable",con);
DataSet ds = new System.Data.DataSet();
dap.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
Defautl.aspx:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
onrowdatabound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Name">
<ItemTemplate >
<asp:Label ID="l1" Text='<%# Bind("name") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Job">
<ItemTemplate >
<asp:Label id="l2" Text='<%# Bind("job") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Status">
<ItemTemplate >
<asp:Label ID="l3" Text='<%# Bind("status") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
ScreenShot:
Mark answer if it help :)

SortCommand Event handler of DataGrid not working

I have created an event handler for the OnSortCommand of DataGrid:
<asp:DataGrid id="dtgBatches" runat="server" Width="100%" CssClass="intTable" EnableViewState="False" DataKeyField="bat_GUID"
GridLines="Horizontal" AllowSorting="True" AutoGenerateColumns="False" AllowPaging="False" >
<SelectedItemStyle BackColor="#FFFF99"></SelectedItemStyle>
<AlternatingItemStyle CssClass="intTableEntry"></AlternatingItemStyle>
<ItemStyle CssClass="intTableEntry2"></ItemStyle>
<HeaderStyle ForeColor="Black" CssClass="tableHeader"></HeaderStyle>
<Columns>
<asp:TemplateColumn >
<HeaderStyle Width="5%"></HeaderStyle>
<ItemStyle HorizontalAlign="Center"></ItemStyle>
<ItemTemplate>
<img src="../images/icons/cog.png" onclick="universalAlert('Loading...',4,false); ViewBatch('<%# DataBinder.Eval(Container.DataItem, "bat_GUID") %>')" alt="view"/>
</ItemTemplate>
</asp:TemplateColumn>
<asp:BoundColumn DataField="bat_Name" SortExpression="bat_Name" HeaderText="<%$ Resources:AI360Resource, lnkbtn_Name %>">
<HeaderStyle Width="10%"></HeaderStyle>
<ItemStyle HorizontalAlign="Left"></ItemStyle>
</asp:BoundColumn>
<asp:BoundColumn DataField="bat_Id" SortExpression="bat_Id" HeaderText="<%$ Resources:AI360Resource, ltxt_ID %>">
<HeaderStyle Width="10%"></HeaderStyle>
<ItemStyle HorizontalAlign="Left"></ItemStyle>
</asp:BoundColumn>
<asp:BoundColumn DataField="bat_Date" SortExpression="bat_Date" HeaderText="<%$ Resources:AI360Resource, alt_date %>" DataFormatString="{0:d}">
<HeaderStyle HorizontalAlign="right" Width="10%"></HeaderStyle>
<ItemStyle HorizontalAlign="Right"></ItemStyle>
</asp:BoundColumn>
<asp:TemplateColumn>
<HeaderStyle Width="1%"></HeaderStyle>
</asp:TemplateColumn>
<asp:BoundColumn DataField="bat_Close_date" SortExpression="bat_Close_date" HeaderText="<%$ Resources:AI360Resource, ltxt_closed %>" DataFormatString="{0:d}">
<HeaderStyle Width="29%"></HeaderStyle>
<ItemStyle HorizontalAlign="Left"></ItemStyle>
</asp:BoundColumn>
<asp:BoundColumn DataField="bat_Cont_Amount" SortExpression="bat_Cont_Amount" HeaderText="<%$ Resources:AI360Resource, alt_receipts %>" DataFormatString="{0:c}">
<HeaderStyle Width="10%"></HeaderStyle>
<ItemStyle HorizontalAlign="Left"></ItemStyle>
</asp:BoundColumn>
<asp:BoundColumn DataField="bat_Disb_Amount" SortExpression="bat_Disb_Amount" HeaderText="<%$ Resources:AI360Resource, alt_disb %>" DataFormatString="{0:c}">
<HeaderStyle Width="25%"></HeaderStyle>
<ItemStyle HorizontalAlign="Left"></ItemStyle>
</asp:BoundColumn>
</Columns>
</asp:DataGrid>
And the code of handler is as below:
protected void dtgBatches_SortCommand(object source, System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
{
string strCurrentSort = dtgBatches.Attributes["SortExpr"];
string strNewSort = e.SortExpression;
if ((strCurrentSort != null) && (strCurrentSort == strNewSort))
{
//reverse direction
strNewSort += " DESC";
}
// Code to Set DataView dv
dv.Sort = strNewSort;
dtgBatches.DataSource = dv;
dtgBatches.DataBind();
}
The problem is that the handler never executes.
The registartion for the handler is done as below:
private void InitializeComponent()
{
this.dtgBatches.SortCommand += new System.Web.UI.WebControls.DataGridSortCommandEventHandler(this.dtgBatches_SortCommand);
}
ViewState needs to be enabled for sorting.
http://msdn.microsoft.com/en-us/library/ms972427.aspx

Categories

Resources