SQL Server table structure:
ChapName varchar(200)
Status varchar(1)
Requirement:
I want to display checkbox in an ASP.NET gridview from Visual Studio 2010
if the value of status column is T, let it be checked and unchecked otherwise.
but it shows only textbox.
I have tried <asp:templatefield> and <asp:itemtemplate> but it throws error if I try to bind this checkbox.
any sample code is required as I am beginner in this field.
The code I tried:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
CheckBox c = (CheckBox)GridView1.FindControl("ChkStatus");
TextBox TB = (TextBox)GridView1.FindControl("Status");
//Response.Write(TB.Text);
if (TB.Text == "T")
{
c.Checked = true;
}
else
{
c.Checked = false;
}
}
The error I got
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web
request. Please review the stack trace for more information about the
error and where it originated in the code.
Exception Details:
System.NullReferenceException: Object reference not set to an instance
of an object.
Aspx markup:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="Comp,QTypeCode" DataSourceID="SDS_QType_Edit"
BackColor="White" BorderColor="#DEDFDE" BorderStyle="None"
BorderWidth="1px"
CellPadding="4" ForeColor="Black" GridLines="Vertical"
AllowPaging="True" AllowSorting="True"
onselectedindexchanged="GridView1_SelectedIndexChanged"
onrowdatabound="GridView1_RowDataBound">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:CommandField ShowEditButton="True" ShowSelectButton="True" />
<asp:BoundField DataField="QTypeCode" HeaderText="QTypeCode"
SortExpression="QTypeCode" InsertVisible="False"
ReadOnly="True" />
<asp:BoundField DataField="Descr" HeaderText="Descr" SortExpression="Descr" />
<asp:CheckBoxField DataField="AnsReq" HeaderText="AnsReq" ReadOnly="True"
SortExpression="AnsReq" />
<asp:CheckBoxField DataField="OptionPrint" HeaderText="OptionPrint"
ReadOnly="True" SortExpression="OptionPrint" />
<asp:BoundField DataField="Status" HeaderText="Status"
SortExpression="Status" />
<asp:BoundField DataField="TransDate" HeaderText="TransDate"
SortExpression="TransDate" />
<asp:BoundField DataField="UserName" HeaderText="UserName"
SortExpression="UserName" />
<asp:TemplateField HeaderText="Check Box" >
<ItemTemplate>
<asp:CheckBox ID ="ChkStatus" Text="text" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle Wrap="False" />
<EmptyDataRowStyle Wrap="False" />
<FooterStyle BackColor="#CCCC99" />
<HeaderStyle Wrap="False" BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<RowStyle Wrap="False" BackColor="#F7F7DE" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White"
Wrap="False" />
<SortedAscendingCellStyle BackColor="#FBFBF2" />
<SortedAscendingHeaderStyle BackColor="#848384" />
<SortedDescendingCellStyle BackColor="#EAEAD3" />
<SortedDescendingHeaderStyle BackColor="#575357" />
</asp:GridView>
Assume you have grid defined as below on asmx
<asp:GridView ID="GridView1" runat="server"
onrowdatabound="GridView1_RowDataBound" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="ChapName" HeaderText="ChapName" />
<asp:TemplateField HeaderText="Status" Visible ="false">
<ItemTemplate>
<asp:Label ID="Status" runat="server" Text='<%# Bind("Status") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Check Box" >
<ItemTemplate>
<asp:CheckBox ID ="ChkStatus" Text="text" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
on Row Data Bound event you can find controls as below
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
CheckBox c = e.Row.FindControl("ChkStatus") as CheckBox;
Label lbl = e.Row.FindControl("Status") as Label;
if (c!= null && lbl != null )
{
c.Checked = (lbl.Text == "T");
}
}
Related
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";
}
}
I'm applying edit functionality on grid view with object data source.I want to take previous value when i click edit button that's need for another purpose here i'm trying to write code but it gives current value.how to get previous value.......hope you can help me
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = (GridView1.Rows[e.RowIndex] as GridViewRow);
string totalQuantity = (row.Cells[5].Controls[0] as TextBox).Text;//It gives current value but i want previous value
string totalPurchasePrice = (row.Cells[6].Controls[0] as TextBox).Text; //It gives current value but i want previous value
GridView1.EditIndex = -1;
//value store in session start
Session["totalQuantity"] = totalQuantity;
Session["totalPurchasePrice"] = totalPurchasePrice;
//value store in session end
}
and grid view code
<asp:GridView ID="GridView1" runat="server" CssClass="dataGridTable" AutoGenerateColumns="False" Width="100%" AllowPaging="True" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="3" DataSourceID="ObjectDataSource1" HeaderStyle-Height="30" OnRowCreated="GridView1_RowCreated" PageSize="30" DataKeyNames="invoiceNumber,productName,productCategory" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" OnRowUpdating="GridView1_RowUpdating">
<Columns>
<asp:CommandField ShowEditButton="true" ShowSelectButton="True" />
<asp:CommandField ShowDeleteButton="true"/>
<asp:BoundField DataField="invoiceNumber" HeaderText="Invoice" ReadOnly="true" SortExpression="invoiceNumber" />
<asp:BoundField DataField="productName" HeaderText="Name" ReadOnly="true" SortExpression="productName" />
<asp:BoundField DataField="productCategory" HeaderText="Category" ReadOnly="true" SortExpression="productCategory" />
<asp:BoundField DataField="totalQuantity" HeaderText="Quantity" SortExpression="totalQuantity" />
<asp:BoundField DataField="totalPurchasePrice" HeaderText="Total Price" SortExpression="totalPurchasePrice" />
<asp:BoundField DataField="salePricePerItem" HeaderText="Sale Price/Item" SortExpression="salePricePerItem" />
<asp:BoundField DataField="comments" HeaderText="Comments" SortExpression="comments" />
<asp:BoundField DataField="date" HeaderText="Date" ReadOnly="true" SortExpression="date" />
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="ImageButton1" runat="server" Height="24px" ImageUrl="~/Images/detailsInfo.png" Width="24px" OnClick="ImageButton1_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="White" ForeColor="#000066" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" CssClass="gridHeaderAlignment" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<RowStyle ForeColor="#000066" HorizontalAlign="Center" VerticalAlign="Middle" />
<HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" />
<SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#007DBB" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#00547E" />
</asp:GridView>
I'm trying to add a Register button to every row in my course gridview so that when the user click on the register button on that particular row, it will register him to that particular course on that row by adding a course registration record into sql.
How should I write my code to insert that row's data into sql?
C#:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Register")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GridView1.Rows[index];
}
ASP.NET:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4"
ForeColor="#333333" GridLines="None" OnSelectedIndexChanged="GridView1_SelectedIndexChanged"
OnRowCommand="GridView1_RowCommand" Width="394px">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" />
<asp:BoundField DataField="Title" HeaderText="Title" ReadOnly="True"></asp:BoundField>
<asp:BoundField DataField="SpeakerName" HeaderText="Speaker" ReadOnly="True" />
<asp:BoundField DataField="startdate" HeaderText="Date" ReadOnly="True" />
<asp:BoundField DataField="Capacity" HeaderText="Capacity" />
<asp:TemplateField HeaderText="Button" ShowHeader="False">
<ItemTemplate>
<asp:Button ID="RegButton" runat="server" CausesValidation="false" CommandName="Register"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" Text="Register" />
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Select" SelectText="Details" ShowSelectButton="True" />
</Columns>
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<SortedAscendingCellStyle BackColor="#FDF5AC" />
<SortedAscendingHeaderStyle BackColor="#4D0000" />
<SortedDescendingCellStyle BackColor="#FCF6C0" />
<SortedDescendingHeaderStyle BackColor="#820000" />
</asp:GridView>
first you should add course Id (primary key) as datakeynames property to GridView1,and then can get the Id on GridView1_RowCommand like below :
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Register")
{
GridViewRow row = (GridViewRow)((Control)e.CommandSource).NamingContainer;
int courseId = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value);
//your other codes
}
so,you have your course Id and by selecting the record you can add current record to sql.hope it helps.
Edit :
also you don't need this part CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" in your aspx page any more
I am trying to get the selected row data and transfer it to a label on the same page. However I cannot get the Gridview.SelectedRow to work with my CommandName. I have tried everything....
I get the error. Object reference not set to an instance of an object. on Label2.Text
Here is my Code:
protected void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
{
// If multiple ButtonField column fields are used, use the
// CommandName property to determine which button was clicked.
if (e.CommandName == "Grab")
{
Label2.Text = GridView1.SelectedRow.Cells[2].Text;
Label3.Text = GridView1.SelectedRow.Cells[3].Text;
Label4.Text = GridView1.SelectedRow.Cells[4].Text;
Label5.Text = GridView1.SelectedRow.Cells[5].Text;
}
}
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" BackColor="White" BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px" CellPadding="4" DataKeyNames="ID" DataSourceID="SqlDataSource1" ForeColor="Black" GridLines="Vertical" CssClass="td" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" Width="574px" onrowcommand="GridView1_RowCommand">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:ImageButton ID="ImageButton2" runat="server" ImageUrl="~/images/edit.png" OnClick="ImageButton2_Click" />
<asp:ImageButton ID="ImageButton1" runat="server" CommandName="Select" ImageUrl="~/images/delete.png" onclientclick=" return confirm('Are you want to Delete this Vehicle?');" />
<asp:ImageButton ID="ImageButton3" runat="server" ImageUrl="~/images/refre.png" CommandName="Grab" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="Year" HeaderText="Year" SortExpression="Year" />
<asp:BoundField DataField="Make" HeaderText="Make" SortExpression="Make" />
<asp:BoundField DataField="Model" HeaderText="Model" SortExpression="Model" />
<asp:BoundField DataField="Submodel" HeaderText="Submodel" SortExpression="Submodel" />
<asp:BoundField DataField="ISENABLED" HeaderText="ISENABLED" SortExpression="ISENABLED" />
</Columns>
<FooterStyle BackColor="#CCCC99" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<RowStyle BackColor="#F7F7DE" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FBFBF2" />
<SortedAscendingHeaderStyle BackColor="#848384" />
<SortedDescendingCellStyle BackColor="#EAEAD3" />
<SortedDescendingHeaderStyle BackColor="#575357" />
</asp:GridView>
Try something like this. Since you're trying to access the values in the command event and not in the OnSelectedIndexChanged event you need to get hold of the row triggering the command event first.
if (e.CommandName == "Grab")
{
GridViewRow row = (GridViewRow)((ImageButton)e.CommandSource).NamingContainer;
if (row != null)
{
Label2.Text = row.Cells[2].Text;
Label3.Text = row.Cells[3].Text;
Label4.Text = row.Cells[4].Text;
Label5.Text = row.Cells[5].Text;
}
}
I have an asp.net page with c# code-behind. I have an event that is triggered in c# when the selected index on a gridview changes... This gridview is bound to an entites-data-source, and I need to find a way to tell my code-behind the id of the object that was selected when it calls the selected_index_changed() method. Any thoughts on how best to do this?
Current event handler code:
protected void VehiclesGridView_SelectedIndexChanged(object sender, EventArgs e)
{
if (ChangeAttemptedId && !IsSavedId)
{
Alert.Show("Dispatch assignment saved... (But you forgot to click Confirm or Cancel!)");
}
IsSavedId = false;
ChangeAttemptedId = true;
int selectedIndex = VehiclesGridView.SelectedIndex + 1;
getNextRide(selectedIndex); //TODO: FIX
}
ASP.NET Code:
<asp:EntityDataSource ID="VehiclesEDS" runat="server" EnableDelete="True"
EnableFlattening="False" EnableInsert="True" EnableUpdate="True"
EntitySetName="Vehicles" ContextTypeName="RamRideOps.RamRideOpsEntities" >
</asp:EntityDataSource>
<asp:UpdatePanel ID="SelectCarUP" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:GridView ID="VehiclesGridView" runat="server" AllowPaging="True"
AllowSorting="True" DataSourceID="VehiclesEDS" AutoGenerateColumns="False"
onselectedindexchanged="VehiclesGridView_SelectedIndexChanged"
BackColor="White" BorderColor="#999999" BorderStyle="None" BorderWidth="1px"
CellPadding="3" GridLines="Vertical" ShowHeaderWhenEmpty="True" AutoPostBack="True">
<AlternatingRowStyle BackColor="#DCDCDC" />
<Columns>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="GVSelectButton" runat="server" CausesValidation="False"
CommandName="Select" Text="Select"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CarNum" HeaderText="Car" ReadOnly="True"
SortExpression="CarNum" />
<asp:BoundField DataField="CurrPassengers" HeaderText="Passengers"
ReadOnly="True" SortExpression="CurrPassengers" />
<asp:BoundField DataField="MaxPassengers" HeaderText="Capacity" ReadOnly="True"
SortExpression="MaxPassengers" />
<asp:BoundField DataField="Status" HeaderText="Status" ReadOnly="True"
SortExpression="Status" />
<asp:BoundField DataField="StartAdd" HeaderText="Pick-Up Address"
ReadOnly="True" SortExpression="StartAdd" />
<asp:BoundField DataField="EndAdd" HeaderText="Drop-Off Address"
ReadOnly="True" SortExpression="EndAdd" />
<asp:BoundField DataField="AvgRideTime" HeaderText="Avg. Ride Time"
ReadOnly="True" SortExpression="AvgRideTime" />
</Columns>
<FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
<HeaderStyle BackColor="#004812" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<RowStyle BackColor="#EEEEEE" ForeColor="Black" />
<SelectedRowStyle BackColor="#C6940D" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#C6940D" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#9F770B" />
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
Error when changing EventArgs e to GridViewSelectEventArgs:
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS0123: No overload for 'VehiclesGridView_SelectedIndexChanged' matches delegate 'System.EventHandler'
Source Error:
Line 90: <asp:UpdatePanel ID="SelectCarUP" runat="server" UpdateMode="Conditional">
Line 91: <ContentTemplate>
Line 92: <asp:GridView ID="VehiclesGridView" runat="server" AllowPaging="True"
Line 93: AllowSorting="True" DataSourceID="VehiclesEDS" AutoGenerateColumns="False"
Line 94: onselectedindexchanged="VehiclesGridView_SelectedIndexChanged"
If the parameter that you want to pass to getNextRide is indeed the same as selected index, then i'd make an event handler like this
protected void VehiclesGridView_SelectedIndexChanged(object sender, GridViewSelectEventArgs e)
{
if (ChangeAttemptedId && !IsSavedId)
{
Alert.Show("Dispatch assignment saved... (But you forgot to click Confirm or Cancel!)");
}
IsSavedId = false;
ChangeAttemptedId = true;
int selectedIndex = e.NewSelectedIndex;
getNextRide(selectedIndex); //TODO: FIX
}
also, inside your event handler, you can access the individual members of your grid view like so: VehiclesGridView.Rows[e.NewSelectedIndex].Cells[i] where i is the index of your cell.
Also, can you post the line where you set the datasource of VehiclesGridView, so that i might be able to come up with a cleaner answer