how to edit and update row values in grid view? - c#

I have a gridview like this :
<asp:GridView ID="gvProducts" runat="server" AutoGenerateEditButton="True" AutoGenerateColumns="False"
OnRowEditing="gvProducts_RowEditing" OnRowUpdating="gvProducts_RowUpdating" CellPadding="4"
ForeColor="#333333" GridLines="None">
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:Label ID="lblPID" runat="server" Text="Product ID"></asp:Label>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblProdID" runat="server" Text='<%#Eval("ProductID")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtProdID" runat="server" Text='<%#Eval("ProductID")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<asp:Label ID="lblPName" runat="server" Text="Product Name"></asp:Label>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblProdName" runat="server" Text='<%#Eval("ProductName")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtProdName" runat="server" Text='<%#Eval("ProductName")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
and here is the code behind page
protected void gvProducts_RowEditing(object sender, GridViewEditEventArgs e)
{
gvProducts.EditIndex = e.NewEditIndex;
}
protected void gvProducts_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int i = e.RowIndex;
object control = gvProducts.Rows[i].FindControl("txtProdID");
//i want to access the new value from the object "control" but i m getting the previous value only
}

try this
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
TextBox txtProdID = (TextBox)gvProducts.Rows[e.RowIndex].FindControl("txtProdID");
TextBox txtProdName = (TextBox)gvProducts.Rows[e.RowIndex].FindControl("txtProdName");
//Call update method
Product.Update(txtProdId,txtProdName);
gvProducts.EditIndex = -1;
//Refresh the gridviwe
BindGrid();
}

You need to check the e.NewValues dictionary for updated data.
I've a sample below, the GridView Template is bound to CategoryName.
OnRowUpdating is fired when the 'Edit' button is clicked.
In the RowUpdating event handler, it fetches the CategoryName data to which the textbox is bound to.
Note: Instead of using TextBox in normal mode use Labels.
<asp:GridView ID='GridView1' runat='server' DataKeyNames='CategoryID' OnRowUpdating='HandleOnGridViewRowUpdating'
DataSourceID='ObjectDataSource1' AutoGenerateColumns='false'>
<Columns>
<asp:CommandField ShowEditButton="true" />
<asp:TemplateField>
<HeaderTemplate>
<asp:Label ID='CategoryName' Text='Category' runat='server'></asp:Label>
</HeaderTemplate>
<ItemTemplate>
<asp:TextBox ID='CategoryNameTextbox' Text='<%# Bind("CategoryName") %>' runat='server'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
code-behind:
public void HandleOnGridViewRowUpdating(object sender, GridViewUpdateEventArgs e)
{
if (e.NewValues["CategoryName"] != null)
{
String newCategoryName = e.NewValues["CategoryName"].ToString();
// process the data;
}
}

Related

How to get the row index of a dynamically created asp.net GridView?

How to get the row index of a dynamically created asp.net GridView so that I can edit the record in a text box outside the GridView.
How to get the row index of a dynamically created asp.net GridView so that I can edit the record in a text box outside the GridView.
This is the GridView:
<asp:GridView ID="GridView1" AutoGenerateColumns="False" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="RefID">
<ItemTemplate>
<asp:Label ID="lbl_Refid" runat="server" Text='<%# Eval("Refid") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date">
<ItemTemplate>
<asp:Label ID="lbl_date" runat="server" Text='<%# Eval("Date") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name Of Company">
<ItemTemplate>
<asp:Label ID="lbl_noc" runat="server" Text='<%# Eval("Name_Of_Company") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Contact/Email">
<ItemTemplate>
<asp:Label ID="lbl_wht_do" runat="server" Text='<%# Eval("Contact") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Remarks">
<ItemTemplate>
<asp:Label ID="lbl_wht_do" runat="server" Text='<%# Eval("Remarks") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:Button ID="btn_edit" runat="server" `enter code here` Text="Button" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>
<asp:GridView ID="GridView1" AutoGenerateColumns="False" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" OnRowCommand = "OnRowCommand">
Use
OnRowCommand = "OnRowCommand"
Now when any action happen on the grid the OnRowCommand event is executed.
protected void OnRowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow gvRow = GridView1.Rows[index];
}
More Info
<ItemTemplate>
<asp:Button ID="Button1" runat="server" Text="Button"
OnClick="MyButtonClick" />
</ItemTemplate>
and your method
protected void MyButtonClick(object sender, System.EventArgs e)
{
//Get the button that raised the event
Button btn = (Button)sender;
//Get the row that contains this button
GridViewRow gvr = (GridViewRow)btn.NamingContainer;
}

I needed to move row from a gridview to a database table How to?

everyone. I needed your help. I am creating an online workshop registration system. I have a inicale gridview that show the all the available workshop for registration during the festival time. I am using a session and check box to get the workshop that the person want into the "shopping cart" on the next page. what I needed to do is after righting a incial order written to an order table in my SQL database. What I am having issues with is when it write the registration data that is stored in an other gridview for the shopping cart. I am writing each row as a new entry into a order detail table. when I do this the program does something very odd. It seem to write all the data from the a gridview that holds all the workshop information on the first page.
code for writing the shopping cart row to the order detail table:
protected void btn_Submit_Click1(object sender, EventArgs e)
{
foreach (GridViewRow row in Basket.Rows)
{
Label lblCatCode = (Label)row.FindControl("lblCatCode");
Label lblTitle = (Label)row.FindControl("lblTitle");
SqlConnection conBasket = new SqlConnection("Data Source=JONS\\SQLEXPRESS;Initial Catalog=OFFFV2;Integrated Security=True");
SqlCommand cmdBasket = new SqlCommand("Insert into OrderDetail(OrderID,CatalogeCode,Title)Values(#OrderID,#CatCode,#Title)", conBasket);
cmdBasket.Parameters.AddWithValue("#OrderID", lblOrderNumber.Text);
cmdBasket.Parameters.AddWithValue("#CatCode", lblCatCode.Text);
cmdBasket.Parameters.AddWithValue("#Title", lblTitle.Text);
try
{
conBasket.Open();
cmdBasket.ExecuteNonQuery();
conBasket.Close();
}
catch (Exception ex)
{
lbl_Error.Text = "A database error has orrued. <br <br />" + "Message: " + ex.Message;
}
}
}
Here is the code for the gridview
<asp:GridView ID="Basket" runat="server" AutoGenerateColumns="False" DataKeyNames="WorkshopID" DataSourceID="BasketData" EnableViewState="False" ShowFooter="True" OnRowCreated="Basket_RowCreate" CellPadding="4" ForeColor="#333333" GridLines="None" >
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Remove">
<ItemTemplate>
<asp:CheckBox ID="cb_BasketRemove" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Cataloge Code" SortExpression="CatalogeCode">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Eval("CatalogeCode") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblCatCode" runat="server" Text='<%# Eval("CatalogeCode") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Title" SortExpression="Title">
<ItemTemplate>
<asp:Label ID="lblTitle" runat="server" Text='<%# Eval("Title") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<strong>
Total Price:
</strong>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Price" SortExpression="Price">
<ItemTemplate>
<asp:Label ID="Price" runat="server" Text='<%# Eval("Price") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<strong>
<asp:Literal ID="TotalPrice" runat ="server" />
</strong>
</FooterTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>
I understand that my last post was unclear and was closed. I am at a loss as why the program is doing what it is doing. I am wondering if it is in connection with the way I get the data from the first gridview to the shopping cart.
Here is the code for the session for the selected row
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btt_Select_Click(object sender, EventArgs e)
{
var selectedWorkshop = GridView1.Rows.Cast<GridViewRow>().Where(row => ((CheckBox)row.FindControl("RegisteredWorkshop")).Checked).Select(row => GridView1.DataKeys[row.RowIndex].Value.ToString()).ToList();
if (Session["cart"] == null)
{
Session["cart"] = selectedWorkshop;
}
else
{
var cart = (List<string>)Session["cart"];
foreach (var workshop in selectedWorkshop)
cart.Add(workshop);
Session["cart"] = cart;
}
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox cb = (CheckBox)row.FindControl("RegisteredWorkshop");
if (cb.Checked)
cb.Checked = false;
}
}
protected void btt_CheckOut_Click(object sender, EventArgs e)
{
if (Session["cart"] != null)
Response.Redirect("Checkout.aspx");
}
}
The code for the select gridview from where the registrant select from the various workshops:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource3" CellPadding="4" DataKeyNames="WorkshopID" ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText ="Register">
<ItemTemplate>
<asp:CheckBox ID="RegisteredWorkshop" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="FestivalYear" HeaderText="Festival Year" />
<asp:BoundField DataField="CatalogeCode" HeaderText="Catalog Code" />
<asp:BoundField DataField="Title" HeaderText="Title" />
<asp:BoundField DataField="WSDescription" HeaderText="Workshop Description" />
<asp:BoundField DataField="DayOffered" HeaderText="Day Offered" />
<asp:BoundField DataField="Lenght" HeaderText="Workshop Lenght" />
<asp:BoundField DataField="BeginingTime" HeaderText="Start Time" />
<asp:BoundField DataField="Price" HeaderText="Workshop Fee" />
<asp:BoundField DataField="WorkshopID" HeaderText="Workshop Id" Visible="False" />
</Columns>
I may be wrong but it looks like your variable naming is off (confusing basket and cart?).
You might need to do something like this:
protected void btn_Submit_Click1(object sender, EventArgs e)
{
var Basket = (List<string>)Session["cart"]; // ADD THIS LINE
foreach (GridViewRow row in Basket.Rows)
{

How should I set gridview pager value when row is hidden

I have an issue where the pager number doesn't get updated automatically when I hide rows in the gridview. Do I need to set the pager value manually? Can someone suggest me on this?
ASPX page
<asp:GridView ID="SearchResults" runat="Server" AutoGenerateColumns="false"
EnableViewState="false" AllowPaging="true" PageSize="50"
OnDataBound ="SearchResults_DataBound"
OnRowDataBound="SearchResults_RowDataBound">
<RowStyle CssClass="EvenRow" />
<AlternatingRowStyle CssClass="OddRow" />
<Columns>
<asp:TemplateField meta:resourceKey="UmSellField">
<ItemStyle CssClass="alpha" />
<HeaderStyle CssClass="alpha" />
<ItemTemplate>
<asp:Label ID="UmSellLabel" runat="server" EnableViewState="false"
Text='<%# GetUnitOfMeasure(Container.DataItem,false) %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
codebehind
protected void SearchResults_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType.Equals(DataControlRowType.DataRow))
{
e.Row.Visible = showRow;
e.Row.Cells[0].Visible = showRow;
}
}
ShowRow is a boolean value that gets set in GetUnitOfMeasure function (not copied here) based on these conditions.

gridview editing and updating

I got a gridview and there is hyperlink column which says update. Upon clicking that page will redirect to another page and particular row values will display in another gridview. and there the user need to edit 1 column and make it update and after that there is a button outside gridview which is send or accept , upon clicking it a mail should get generate it should take updated grid values and send it to he other user and page should get redirected to previous page.
aspx code of gridview
<asp:GridView ID="GridView1" 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="70px"
ShowFooter="True" ShowHeaderWhenEmpty="True" OnRowCommand="GridView1_RowCommand"
OnRowDataBound="GridView1_RowDataBound" OnRowEditing="GridView1_RowEditing"
onselectedindexchanged="GridView1_SelectedIndexChanged" OnRowUpdating="GridView1_RowUpdating"
Width="796px">
<Columns>
<asp:BoundField DataField="LeaveID" Visible="false">
<FooterStyle BackColor="#0061C1" />
<HeaderStyle BackColor="#0061C1" ForeColor="White" HorizontalAlign="Center"
VerticalAlign="Middle" />
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="10px" />
</asp:BoundField>
<asp:TemplateField HeaderText="Applied By">
<ItemTemplate>
<asp:Label
ID="LoggedInUser" runat="server" Font-Names="Verdana" Font-Size="X-Small"
Height="24px" Text='<%# Eval("LoggedInUser")%>' Width="100px"></asp:Label>
</ItemTemplate>
<FooterStyle BackColor="#0061C1" />
<HeaderStyle BackColor="#0061C1" ForeColor="White"></HeaderStyle>
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Begin Date">
<ItemTemplate>
<asp:Label
ID="BeginDate" runat="server" DataFormatString="{0:dd/MM/yyyy}"
Font-Names="Verdana" Text='<%# Eval("BeginDate","{0:dd/MM/yyyy}")%>' Font-Size="X-Small" Height="20px"
Width="100px"></asp:Label>
</ItemTemplate>
<FooterStyle BackColor="#0061C1" />
<HeaderStyle BackColor="#0061C1" ForeColor="White"></HeaderStyle>
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="End Date">
<ItemTemplate>
<asp:Label
ID="EndDate" runat="server" Font-Names="Verdana" Font-Size="X-Small"
Height="20px" Text='<%# Eval("EndDate","{0:dd/MM/yyyy}")%>' Width="100px"></asp:Label>
</ItemTemplate>
<FooterStyle BackColor="#0061C1" />
<HeaderStyle BackColor="#0061C1" ForeColor="White"></HeaderStyle>
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Num of Days">
<ItemTemplate>
<asp:Label
ID="NumofDays" runat="server" Font-Names="Verdana" Font-Size="X-Small"
Height="20px" Text='<%# Eval("NumofDays")%>' Width="100px"></asp:Label>
</ItemTemplate>
<FooterStyle BackColor="#0061C1" />
<HeaderStyle BackColor="#0061C1" ForeColor="White"></HeaderStyle>
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Type of Leave ">
<ItemTemplate>
<asp:Label
ID="LeaveType" runat="server" Font-Names="Verdana" Font-Size="X-Small"
Height="20px" Text='<%# Eval("TypeofLeave")%>' Width="100px"></asp:Label>
</ItemTemplate>
<FooterStyle BackColor="#0061C1" />
<HeaderStyle BackColor="#0061C1" ForeColor="White"></HeaderStyle>
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:Label
ID="Status" runat="server" Font-Names="Verdana" Font-Size="X-Small"
ForeColor="Black" Height="20px" Text='<%# Eval("Status")%>' Width="100px"></asp:Label>
</ItemTemplate>
<FooterStyle BackColor="#0061C1" />
<HeaderStyle BackColor="#0061C1" ForeColor="White"></HeaderStyle>
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Reason for Reject">
<ItemTemplate>
<asp:Label ID="RejectReason"
runat="server" Font-Names="Verdana" Font-Size="X-Small" ForeColor="Black"
Height="20px" Text='<%# Eval("RejectReason")%>' Enabled="true" Visible="true" Width="100px"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TxtRejectReason"
runat="server" Font-Names="Verdana" Font-Size="X-Small" ForeColor="Black"
Height="20px" Text='<%# Eval("RejectReason")%>' Enabled="true" Visible="true" Width="100px"></asp:TextBox>
</EditItemTemplate>
<FooterStyle BackColor="#0061C1" />
<HeaderStyle BackColor="#0061C1" ForeColor="White"></HeaderStyle>
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle"></ItemStyle>
</asp:TemplateField>
<asp:BoundField DataField="LogdInUser" Visible="false" >
<FooterStyle BackColor="#0061C1" />
<HeaderStyle BackColor="#0061C1" ForeColor="White" HorizontalAlign="Center"
VerticalAlign="Middle" />
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="100px" />
</asp:BoundField>
<asp:BoundField DataField="Manager" Visible="false" >
<FooterStyle BackColor="#0061C1" />
<HeaderStyle BackColor="#0061C1" ForeColor="White" HorizontalAlign="Center"
VerticalAlign="Middle" />
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="100px" />
</asp:BoundField>
<asp:CommandField ShowEditButton="true" ButtonType="Button" EditText="Edit">
<ControlStyle Width="50" />
</asp:CommandField>
</Columns>
</asp:GridView>
i need to edit RejectReason Column.
cs page
protected void Page_Load(object sender, EventArgs e)
{
MTMSDTO objc = new MTMSDTO();
if (!IsPostBack)
{
int LeaveID = 0;
int.TryParse(Request.QueryString["LeaveID"], out LeaveID);
objc.LeaveID = LeaveID;
objc.RejectReason = TxtRejectReason.Text;
DataSet lapp = obj.GetLeaveApproved(objc);
DataView LApp = new DataView();
LApp.Table = lapp.Tables[0];
GridView1.DataSource = LApp;
GridView1.DataBind();
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataBind();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int LeaveID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());
TextBox TxtRejectReason = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TxtRejectReason");
GridView1.EditIndex = -1;
GridView1.DataBind();
}
once i click edit button in gridview it shows no records
please help me
Try below code:
<asp:GridView ID="GridView1" runat="server" Width = "550px"
AutoGenerateColumns = "false" Font-Names = "Arial"
Font-Size = "11pt" AlternatingRowStyle-BackColor = "#C2D69B"
HeaderStyle-BackColor = "green" AllowPaging ="true" ShowFooter = "true"
OnPageIndexChanging = "OnPaging" onrowediting="EditCustomer"
onrowupdating="UpdateCustomer" onrowcancelingedit="CancelEdit"
PageSize = "10" >
<Columns>
<asp:TemplateField ItemStyle-Width = "30px" HeaderText = "CustomerID">
<ItemTemplate>
<asp:Label ID="lblCustomerID" runat="server"
Text='<%# Eval("CustomerID")%>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtCustomerID" Width = "40px"
MaxLength = "5" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField><asp:TemplateField ItemStyle-Width = "100px" HeaderText = "Name">
<ItemTemplate>
<asp:Label ID="lblContactName" runat="server"
Text='<%# Eval("ContactName")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtContactName" runat="server"
Text='<%# Eval("ContactName")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtContactName" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "150px" HeaderText = "Company">
<ItemTemplate>
<asp:Label ID="lblCompany" runat="server"
Text='<%# Eval("CompanyName")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtCompany" runat="server"
Text='<%# Eval("CompanyName")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtCompany" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkRemove" runat="server"
CommandArgument = '<%# Eval("CustomerID")%>'
OnClientClick = "return confirm('Do you want to delete?')"
Text = "Delete" OnClick = "DeleteCustomer"></asp:LinkButton>
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="btnAdd" runat="server" Text="Add"
OnClick = "AddNewCustomer" />
</FooterTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Columns>
<AlternatingRowStyle BackColor="#C2D69B" />
</asp:GridView>
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
private void BindData()
{
}
protected void AddNewCustomer(object sender, EventArgs e)
{
string CustomerID=((TextBox)GridView1.FooterRow.FindControl("txtCustomerID")).Text;
string Name = ((TextBox)GridView1.FooterRow.FindControl("txtContactName")).Text;
string Company = ((TextBox)GridView1.FooterRow.FindControl("txtCompany")).Text;
//Your Code here...
}
protected void EditCustomer(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindData();
}
protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindData();
}
protected void UpdateCustomer(object sender, GridViewUpdateEventArgs e)
{
string CustomerID = ((Label)GridView1.Rows[e.RowIndex]
.FindControl("lblCustomerID")).Text;
string Name = ((TextBox)GridView1.Rows[e.RowIndex]
.FindControl("txtContactName")).Text;
string Company = ((TextBox)GridView1.Rows[e.RowIndex]
.FindControl("txtCompany")).Text;
//Your code here...
}
protected void DeleteCustomer(object sender, EventArgs e)
{
LinkButton lnkRemove = (LinkButton)sender;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "delete from customers where " +
"CustomerID=#CustomerID;" +
"select CustomerID,ContactName,CompanyName from customers";
cmd.Parameters.Add("#CustomerID", SqlDbType.VarChar).Value
= lnkRemove.CommandArgument;
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
Use code when gridview edit,
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView gridView1= (GridView)sender;
// Change the row state
gridView1.Rows[e.NewEditIndex].RowState = DataControlRowState.Edit;
}
For Update(this is sample code)
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridView gv = (GridView)sender;
GridViewRow gvr = (GridViewRow)gv.Rows[e.RowIndex];
TextBox TxtRejectReason= (TextBox)gvr.FindControl("TxtRejectReason");
string s = TxtRejectReason.Text;
GridView.EditIndex = -1;
GridView.DataBind();
}

How to call a command of a rad grid

i have a rad grid with the following code
<telerik:GridTemplateColumn>
<ItemTemplate>
<asp:LinkButton ID="Delete" Text="Remove &raquo"
CommandArgument='<%# Eval("ApartmentId") %>'
CommandName="RemoveItem" CssClass="Button" runat="server" />
</ItemTemplate>
</telerik:GridTemplateColumn>
and .CS code as follows
protected void radGrid_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Page")
{
}
else
{
if (e.CommandName == "RemoveItem")
{
Apartments apartAdmin = new Apartment();
bool deleted = apartAdmin.Delete(int.Parse(e.CommandArgument.ToString());
if (deleted)
{
radGrid.Rebind();
}
}
}
}
My problem is that when I debug it, say I add the breakpoint to this event, it is never fired, is like if it does not see the event for some reason... Can anyone see what the problem may be? This is the mark up of the grid at the top
<telerik:RadGrid ID="radGrid" ShowFooter="true" ShowHeader="true" CaptionAlign="Left"
runat="server" ForeColor="Black" CellPadding="4" AutoGenerateColumns="False"
CssClass="Grid" Width="100%" GridLines="None" OnRowCommand="radGrid_RowCommand"
OnNeedDataSource="radGrid_NeedDataSource" AllowPaging="True" AllowSorting="true">
<MasterTableView DataKeyNames="ApartmentID,ApartmentTypeID">
<CommandItemSettings ShowRefreshButton="true" ShowAddNewRecordButton="false" />
<Columns>
<telerik:GridTemplateColumn>
<ItemTemplate>
<asp:LinkButton ID="Delete" Text="Remove &raquo"
CommandArgument='<%# Eval("ApartmentId") %>'
CommandName="RemoveItem" CssClass="Button" runat="server" />
</ItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
<NoRecordsTemplate>
No related items found</NoRecordsTemplate>
</MasterTableView>
<FooterStyle CssClass="FooterStyle" />
<ItemStyle CssClass="RowStyle" />
<HeaderStyle CssClass="HeaderStyle" />
<AlternatingItemStyle CssClass="AlternatingRowStyle" />
<PagerStyle CssClass="PagerStyle" FirstPageText="First" LastPageText="Last" Mode="NextPrevAndNumeric"
AlwaysVisible="true" />
</telerik:RadGrid>
You have a linkbutton inside an itemtemplate, add a handler for OnClick on the linkbutton itself and the event will surely be fired.
For example:
protected void LinkButton1_Click(Object sender, EventArgs
{
LinkButton button = sender as LinkButton;
Apartments apartAdmin = new Apartment();
bool deleted = apartAdmin.Delete(int.Parse(button.CommandArgument.ToString());
if (deleted)
{
radGrid.Rebind();
}
}

Categories