Editing a Bound Gridview Error - c#

I'm implementing an "edit" feature on my Gridview bound to my "books" table. I'm receiving an error on RowEditingEvent wasn't handled. I don't understand where I'm going wrong or if I'm missing a reference somewhere but it seems to me that everything is handled.
public partial class AddEdit_Text_Books : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = new DataTable();
string query = "select * from textBooks ";
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["HUTDMSConnectionString"].ToString()))
using (SqlDataAdapter adapter = new SqlDataAdapter(query, connection))
adapter.Fill(dt);
ViewState["allBooks"] = dt;
this.BindGrid();
}
}
protected void BindGrid()
{
GridView1.DataSource = ViewState["allBooks"] as DataTable;
GridView1.DataBind();
}
protected void OnRowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
this.BindGrid();
}
protected void OnUpdate(object sender, EventArgs e)
{
GridViewRow row = (sender as LinkButton).NamingContainer as GridViewRow;
string name = (row.Cells[0].Controls[0] as TextBox).Text;
string country = (row.Cells[1].Controls[0] as TextBox).Text;
DataTable dt = ViewState["allBooks"] as DataTable;
ViewState["allBooks"] = dt;
GridView1.EditIndex = -1;
this.BindGrid();
}
protected void OnCancel(object sender, EventArgs e)
{
GridView1.EditIndex = -1;
this.BindGrid();
}
}
}
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False" DataKeyNames="BookID" Width="1482px" CellPadding="4" ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:BoundField DataField="thirteenISBN" HeaderText="thirteenISBN" SortExpression="thirteenISBN" />
<asp:BoundField DataField="CourseID" HeaderText="CourseID" SortExpression="CourseID" />
<asp:BoundField DataField="BookTitle" HeaderText="BookTitle" SortExpression="BookTitle" />
<asp:BoundField DataField="Ancillary" HeaderText="Ancillary" SortExpression="Ancillary" />
<asp:BoundField DataField="BookActive" HeaderText="BookActive" SortExpression="BookActive" />
<asp:BoundField DataField="ActiveDate" HeaderText="ActiveDate" SortExpression="ActiveDate" />
<asp:BoundField DataField="InactiveDate" HeaderText="InactiveDate" SortExpression="InactiveDate" />
<asp:BoundField DataField="Author" HeaderText="Author" SortExpression="Author" />
<asp:BoundField DataField="BookID" HeaderText="BookID" InsertVisible="False" ReadOnly="True" SortExpression="BookID" />
<asp:BoundField DataField="Notes" HeaderText="Notes" SortExpression="Notes" />
<asp:BoundField DataField="eISBN" HeaderText="eISBN" SortExpression="eISBN" />
<asp:BoundField DataField="ebookAvailable" HeaderText="ebookAvailable" SortExpression="ebookAvailable" />
<asp:BoundField DataField="VendorISBN" HeaderText="VendorISBN" SortExpression="VendorISBN" />
<asp:BoundField DataField="tenISBN" HeaderText="tenISBN" SortExpression="tenISBN" />
<asp:BoundField DataField="EditionAndDate" HeaderText="EditionAndDate" SortExpression="EditionAndDate" />
<asp:BoundField DataField="Publisher" HeaderText="Publisher" SortExpression="Publisher" />
<asp:BoundField DataField="Imprint" HeaderText="Imprint" SortExpression="Imprint" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton Text="Edit" runat="server" CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton Text="Update" runat="server" OnClick="OnUpdate" />
<asp:LinkButton Text="Cancel" runat="server" OnClick="OnCancel" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:HUTDMSConnectionString %>" SelectCommand="SELECT [thirteenISBN], [CourseID], [BookTitle], [Ancillary], [BookActive], [ActiveDate], [InactiveDate], [Author], [BookID], [Notes], [eISBN], [ebookAvailable], [VendorISBN], [tenISBN], [EditionAndDate], [Publisher], [Imprint] FROM [textBooks]"></asp:SqlDataSource>

You have not registered onediting event in gridview definition.
Add OnRowEditing ="OnRowEditing" in below gridview definition.
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AutoGenerateColumns="False" DataKeyNames="BookID" Width="1482px"
CellPadding="4" ForeColor="#333333" GridLines="None" OnRowEditing ="OnRowEditing">

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";
}
}

Gridview rowcommand

I have a little problem when I go to my gridview in website my button for row command doesn't work. I don't know why.
This is my code for the page:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Ver")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow selectedRow = GridView1.Rows[index];
Session["Imagem"] = GridView1.DataKeys[index]["Imagem"];
Session["Nome"] = GridView1.DataKeys[index]["Nome"];
Session["Preço"] = GridView1.DataKeys[index]["Preço"];
Session["Descricao"] = GridView1.DataKeys[index]["Descricao"];
Session["Categoria"] = GridView1.DataKeys[index]["Categoria"];
Session["id"] = GridView1.DataKeys[index]["Id"];
Session["estado"] = GridView1.DataKeys[index]["estado"];
GridView1.DataBind();
Response.Redirect("Detalhes.aspx");
}
}
And my gridview markup is this:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="Imagem ,Nome,Preço,Descricao,Categoria,id,estado"
DataSourceID="SqlShop" OnRowCommand="GridView1_RowCommand"
BackColor="White" BorderColor="#3366CC" BorderStyle="None"
BorderWidth="1px" CellPadding="4" style="margin-top: 0px">
<Columns>
<asp:TemplateField HeaderText="Imagem" SortExpression="Imagem">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Imagem") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("Imagem") %>' Height="8%" Width="8%" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Nome" HeaderText="Nome" SortExpression="Nome" />
<asp:BoundField DataField="Preço" HeaderText="Preço" SortExpression="Preço" />
<asp:BoundField DataField="Descricao" HeaderText="Descricao" SortExpression="Descricao" />
<asp:BoundField DataField="Categoria" HeaderText="Categoria" SortExpression="Categoria" />
<asp:ButtonField ButtonType="Button" CommandName="Select" Text="ver" />
</Columns>
<FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
<HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />
<PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />
<RowStyle BackColor="White" ForeColor="#003399" />
<SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
<SortedAscendingCellStyle BackColor="#EDF6F6" />
<SortedAscendingHeaderStyle BackColor="#0D4AC4" />
<SortedDescendingCellStyle BackColor="#D6DFDF" />
<SortedDescendingHeaderStyle BackColor="#002876" />
</asp:GridView>
<asp:SqlDataSource ID="SqlShop" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT * FROM [Produtos]">
</asp:SqlDataSource>
Command name is incorrect in the C# code
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select") //this part
{
int index = Convert.ToInt32(e.CommandArgument);
...
...
Response.Redirect("Detalhes.aspx");
}
}
Or
You can change the values ButtonField parameters as
<asp:ButtonField ButtonType="Button" CommandName="ver" Text="Select" />

Adding record to sql with gridview rowcommand buttonfield

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

Gridview Command and Selected Row

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;
}
}

Change background color of gridview row while processing

What I need to do is to highlight each row when it is processing to show the process progress, the gridview may contain almost one thousands of row. below is the code I have written but which doesn't work.
Please can someone help me.
<
asp:GridView ID="gdview1" runat="server" BackColor="White"
BorderColor="#DEDFDE" BorderStyle="Solid" BorderWidth="1px" CellPadding="4"
ForeColor="Black" GridLines="Vertical" Font-Names="Calibri"
Font-Size="Small" AutoGenerateColumns="False"
OnRowDataBound="gdview1_RowDataBound"
OnSelectedIndexChanged="gdview1_SelectedIndexChanged">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkBxHeader" OnCheckedChanged="chkSelect_CheckedChanged" AutoPostBack="true" runat="server" />
</HeaderTemplate>
<EditItemTemplate>
<asp:CheckBox ID="chkNUM" runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkNUM" runat="server" DataField="ColNUM" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Row#">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ColNUM" HeaderText="Contract #" />
<asp:BoundField DataField="Col1" HeaderText="Suffix" />
<asp:BoundField DataField="Col2" HeaderText="First Name" />
<asp:BoundField DataField="Col3" HeaderText="Last Name" />
<asp:BoundField DataField="Col4" HeaderText="Street" />
<asp:BoundField DataField="Col5" HeaderText="City" />
<asp:BoundField DataField="Col6" HeaderText="Zip" />
</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>
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void butChargeCreditCards_Click(object sender, EventArgs e)
{
DataTable tblContrts = (DataTable) Session["tblContrts"];
foreach (GridViewRow row in gdview1.Rows)
{
CheckBox chkbx = (CheckBox) row.FindControl("chkNUM");
if (chkbx != null && chkbx.Checked)
{
gdview1_SelectedIndexChanged(row,e);
string SS = chkbx.Text.ToString();
string strResults = method1;
}
}
}
protected void gdview1_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (GridViewRow row in gdview1.Rows)
{
if (row.RowIndex == gdview1.SelectedIndex)
{
row.BackColor = ColorTranslator.FromHtml("#A1DCF2");
}
else
{
row.BackColor = ColorTranslator.FromHtml("#FFFFFF");
}
}
}
}
}
Have you tried it by using the "OnRowDataBound" or "OnRowCreated" Event of the Grid and write the color-highliting in code behind?
Something like this?
http://www.java2s.com/Code/ASP/ADO.net-Database/UsingtheRowCreatedEventtoprogrammaticallychangethestyle.htm
But maybe you have a problem because the loading would be too fast to really notice?

Categories

Resources