Unable to Update GridView in ASP.NET C# - c#

I am trying to update and display a Value present in my GridView. What it does is that it obtains a value present in the label and switches to TextBox when I try to update it. Afterwards, I would like to display that particular value in a label outside of the GridView.
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%#Eval("Product_Quantity") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%#Eval("Product_Quantity") %>'></asp:TextBox>
</EditItemTemplate>
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
dt = new DataTable();
dt = (DataTable)Session["anime"];
dt.Rows[e.RowIndex]["Product_Quantity"] = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox2")).Text;
Session["anime"] = dt;
GridView1.EditIndex = -1;
FillGrid();
Response.Redirect("view_cart.aspx");
}
protected void GridView1_RowDataBound1(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView drv = e.Row.DataItem as DataRowView;
if (drv != null)
{
sum += Convert.ToInt32(((Label)e.Row.Cells[4].FindControl("Label4")).Text);
results.Text = sum.ToString();
}
}
}
Whenever I try to Update the row, it will return : 'Object reference not set to an instance of an object.' at sum += Convert.ToInt32(((Label)e.Row.Cells[4].FindControl("Label4")).Text);
Any ideas on how to solve this?

When you edit the row, the EditTemplate is used. And in the there is no Label4. So the control cannot be found and the code will throw the exception. You then have to search for the TextBox2 control.
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%#Eval("Product_Quantity") %>'></asp:TextBox>
</EditItemTemplate>

I managed to solve this issue by doing the following:-
protected void GridView1_RowDataBound1(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowState == DataControlRowState.Edit)
{
}
else if (e.Row.RowType == DataControlRowType.DataRow)
{
sum += Convert.ToInt32(((Label)e.Row.Cells[4].FindControl("Label4")).Text);
results.Text = sum.ToString();
}
}

Related

selecting the row in gridview using row index

protected void select_click(object sender, GridViewCommandEventArgs e)
{
try
{
DBLibrary db = new DBLibrary();
int index = Convert.ToInt32(e.CommandArgument);
* string FeeId = gridv1.Rows[index].Cells[1].Text;*
if (e.CommandName == "Select")
{
string str = "SELECT AnuFeeMaster.FeeId ,AnuFeeMaster.StudentId, Tbl_Student.SName, AnuFeeMaster.Month, AnuFeeMaster.Year, AnuFeeMaster.FeeAmount, " +
" AnuFeeMaster.PaidAmount FROM AnuFeeMaster INNER JOIN Tbl_Student ON AnuFeeMaster.StudentId = Tbl_Student.StudentId where ( AnuFeeMaster.FeeId ='" + FeeId + "')";
SqlDataReader dr = db.ExecuteReader(str);
while (dr.Read())
{
Session["name"] = dr["sname"].ToString();
Session["id"] = dr["StudentId"].ToString();
Session["mth"] = dr["Month"].ToString();
Session["yr"] = dr["Year"].ToString();
Session["tot"] = dr["FeeAmount"].ToString();
}
}
}
catch { }
}
Above is my code what i used to access that i am not getting the value r data from dat Please suggest me, * mark which i used that show where i am getting the error
create proper grid rowcommand Event
aspx code
<asp:GridView ID="Gv" runat="server" AllowPaging="true" OnRowCommand="Gv_RowCommand" PageSize="10" EmptyDataText="No Records Found !">
<Columns>
<asp:TemplateField HeaderText="Action" ItemStyle-Width="20%">
<ItemTemplate>
<asp:LinkButton ID="lnkview" runat="server" CommandArgument='<%#Eval("Demo_Code") %>' CommandName="select" ></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Coulmn1" HeaderText="Coulmn2" />
<asp:BoundField DataField="Coulmn2" HeaderText="Coulmn2" />
</Columns>
</asp:GridView>
aspx.cs Code
protected void Gv_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "select")
{
}
}
You should properly use RowCommand event of gridview.
void CustomersGridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if(e.CommandName=="Select")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow selectedRow = CustomersGridView.Rows[index];
}
}
You can catch the button click event like below:
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;
}

How to fill selected value to a grid from another grid?

I have a Grid1 with check box, Now I want to store Grid1 selected values into another grid grid2. How can I do this?
My Grid1 is
<asp:GridView ID="GridView1" runat="server" HorizontalAlign="Center" DataKeyNames="ShiftID"
Width="177px" onrowdatabound="GridView1_RowDataBound1">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="ChbGrid" runat="server" oncheckedchanged="ChbGrid_CheckedChanged" />
</ItemTemplate>
<HeaderTemplate>
<asp:CheckBox ID="ChbGridHead" runat="server" AutoPostBack="True"
Font-Bold="True" oncheckedchanged="ChbGridHead_CheckedChanged" />
</HeaderTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Gridview2 is
<asp:GridView ID="GridView2" runat="server" BackColor="#DEBA84"
BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3"
CellSpacing="2">
</asp:GridView>
I have some function
protected void ChbGrid_CheckedChanged(object sender, EventArgs e)
{
CheckBox checkstatus = (CheckBox)sender;
GridViewRow row = (GridViewRow)checkstatus.NamingContainer;
}
protected void ChbGridHead_CheckedChanged(object sender, EventArgs e)
{
CheckBox chkheader = (CheckBox)GridView1.HeaderRow.FindControl("ChbGridHead");
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox chkrow = (CheckBox)row.FindControl("ChbGrid");
if (chkheader.Checked == true)
{
chkrow.Checked = true;
{
}
}
else
{
chkrow.Checked = false;
}
}
}
protected void GridView1_RowDataBound1(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[1].Visible = false;
}
What changes I should made to get my expected output. My GridView1 conatins ShiftID,ShiftName,ShiftTime and Date. How to generate query to dispaly selected Gridview1 item in Griview2
Write this in Source file
<asp:Button ID="btnGetSelected" runat="server" Text="Get selected records" OnClick="GetSelectedRecords" />
On the click of the Button the following event handler is executed. A loop is executed over the GridView Data Rows and CheckBox is referenced.
protected void GetSelectedRecords(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[2] { new DataColumn("Name"), new DataColumn("Country") });
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = (row.Cells[0].FindControl("chkRow") as CheckBox);
if (chkRow.Checked)
{
string name = row.Cells[1].Text;
string country = (row.Cells[2].FindControl("lblCountry") as Label).Text;
dt.Rows.Add(name, country);
}
}
}
gvSelected.DataSource = dt;
gvSelected.DataBind();
}
For more information us this links
GridView with CheckBox: Get Selected Rows in ASP.Net
Transfer Selected Rows from one GridView to Another in Asp.net

Enable and disable link button on gridview

I wants to enable or disable linkbutton on some rows of gridview based on condition.. Can i enable linkbutton on one row and disable it on another row of same grid view ??my code is here
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{LinkButton lnk2 = (LinkButton)e.Row.FindControl("LinkButton2");
if (e.Row.RowType == DataControlRowType.DataRow)
{
SqlCommand cmd12 = new SqlCommand("Select testsession_status from student_vs_testsession_details where testsession_id='" + v_testid.Text + "' ", con12);
SqlDataReader dr12 = cmd12.ExecuteReader();
while (dr12.Read())
{
string test_status = dr12[0].ToString();
LinkButton lnk2 = (LinkButton)e.Row.FindControl("LinkButton2");
foreach (GridViewRow row in GridView1.Rows)
{
if (v_testtype == "Theory Test" && test_status == "Completed")
{
lnk2.Visible = true;
}
else
{
lnk2.Visible = false;
}
}
}
Yes you can easily do it in RowdataBound Event, but you have used lnk2.Visible property in your code.
you may be using Visible property for another requirement but just want to confirm you that it is used to show/hide the Linkbutton only. To enable/disble a Linkbutton, use Enabled property of Linkbutton. as:
lnk2.Enabled = true;// to enable linkbutton.
lnk2.Enabled = false;// to disable linkbutton.
If You want to do it using rowindex, then you can e.Row.RowIndex to find the current row index inside 'RowDatabound` event of gridview. as:
if(e.Row.RowIndex==2)
{
LinkButton lnk2 = (LinkButton)e.Row.FindControl("LinkButton2");
lnk2.Enabled=false;
}
If you want to enable/ disable Linkbutton based on value of some other column in the same row, then you can do the same inside Rowdatabound event. as:
string Namecolumnvalue = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "Name"));
LinkButton lnk2 = (LinkButton)e.Row.FindControl("LinkButton2");
if(Namecolumnvalue =="Disable")
{
lnk2.Enabled=false;
}
else{
lnk2.Enabled=true;
}
--------aspx page code---------
<asp:GridView ID="gvLibrary" runat="server" AutoGenerateColumns="False" Width="100%" DataKeyNames="LibMstRefNo"
EmptyDataText="No Client Found" CssClass="table table-striped table-bordered" OnRowDataBound="gvLibrary_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Issue">
<ItemTemplate>
<asp:LinkButton ID="lnkIssue" runat="server" Text="Issue" OnClick="lnkIssue_Click"></asp:LinkButton>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left" />
<ItemStyle HorizontalAlign="Left" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Receive">
<ItemTemplate>
<asp:LinkButton ID="lnkReceive" runat="server" Text="Receive" OnClick="lnkReceive_Click" OnClientClick="return confirm('Are you Sure?')"></asp:LinkButton>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left" />
<ItemStyle HorizontalAlign="Left" />
</asp:TemplateField>
</Columns>
</asp:GridView>
------------aspx.cs page code------------------
protected void gvLibrary_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string nbps = e.Row.Cells[8].Text;
if(nbps== " ")
{
nbps = "";
}
else
{
nbps = e.Row.Cells[8].Text;
}
if (nbps == "")
{
LinkButton btn = (LinkButton)e.Row.FindControl("lnkissue");
LinkButton btn1 = (LinkButton)e.Row.FindControl("lnkReceive");
btn.Enabled = true;
btn1.Enabled = false;
btn1.ForeColor = System.Drawing.Color.Red;
}
else
{
LinkButton btn = (LinkButton)e.Row.FindControl("lnkissue");
LinkButton btn1 = (LinkButton)e.Row.FindControl("lnkReceive");
btn.Enabled = false;
btn.ForeColor = System.Drawing.Color.Red;
btn1.Enabled = true;
}
}
}

GridView row not updating, text from textbox in gridview edit template not coming

I have grid view in which I want to update row but it is not happening. The datasource is a DataTable. Please help.
Below is the markup
<asp:GridView ID="GrdV" runat="server" AutoGenerateColumns="false"
OnRowEditing="GrdV_RowEditing" OnRowUpdating="GrdV_RowUpdating">
<Columns>
<asp:TemplateField HeaderText="Clip Description">
<ItemTemplate>
<asp:Label ID="lblDescrptn" runat="server" Text='<%# Bind("Description") %>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="descTbx" runat="server" Text='<%# Bind("Description") %>'>
</asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Columns>
and this is code behind
protected void GrdV_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
// Retrieve the row being edited.
int index = GrdV.EditIndex;
GridViewRow row = GrdV.Rows[index];
TextBox t1 = row.FindControl("descTbx") as TextBox;
DataTable dt = (DataTable)Session["tmdataTable"];
dt.Rows[index]["Description"] = t1.Text; //Description is a column of my DataTable
dt.AcceptChanges();
GrdV.EditIndex = -1;
GrdV.DataSource = dt;
GrdV.DataBind();
}
On debugging , I find that textbox is passing empty string t1.Text ="" even after I have filled textbox with new values.
I think the error is in line
TextBox t1 = row.FindControl("descTbx") as TextBox;
PageLoad code
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GrdV.DataSource = Session["tmdataTable"];
GrdV.DataBind();
}
DataTable Finaldt = getTable();
GrdV.DataSource = Finaldt;
GrdV.DataBind();
Session["tmdataTable"] = Finaldt;
}
EditIndex isn't available, you need e.RowIndex from the GridViewUpdateEventArgs
// Retrieve the row being edited.
DataTable dt = (DataTable)Session["tmdataTable"];
GridViewRow row = GrdV.Rows[e.RowIndex];
TextBox t1 = row.FindControl("descTbx") as TextBox;
dt.Rows[row.DataItemIndex]["Description"] = t1.Text; //Description is a column of my DataTable
dt.AcceptChanges();
GrdV.EditIndex = -1;
GrdV.DataSource = dt;
GrdV.DataBind();
Alter your code a bit and check. Change EditIndex to e.RowIndex
protected void GrdV_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = GrdV.Rows[e.RowIndex]; // this line is changed
TextBox t1 = row.FindControl("descTbx") as TextBox;
DataTable dt = (DataTable)Session["tmdataTable"];
dt.Rows[row.DataItemIndex]["Description"] = t1.Text; //Description is a column of my DataTable
dt.AcceptChanges();
GrdV.EditIndex = -1;
GrdV.DataSource = dt;
GrdV.DataBind();
}
Have you done this:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
GrdV.DataSource = Session["tmdataTable"];
GrdV.DataBind();
}
}
protected void GrdV_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
if (e.Item is GridDataItem)
{
// Retrieve the row being edited.
int index = GrdV.EditIndex;
GridViewRow row = GrdV.Rows[index];
TextBox t1 = row.FindControl("descTbx") as TextBox;
DataTable dt = (DataTable)Session["tmdataTable"];
dt.Rows[index]["Description"] = t1.Text; //Description is a column of my DataTable
dt.AcceptChanges();
GrdV.EditIndex = -1;
GrdV.DataSource = dt;
GrdV.DataBind();
}
}

Binding dropdownlist inside gridview edititemtemplate

I'm not able to bind my dropdownlist present in edititem template . I am getting null reference when i try to access it.
My design:
<asp:TemplateField HeaderText ="Category">
<ItemTemplate >
<asp:Label ID="drpcategory" Text ='<%#Bind("category") %>' runat ="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="drpcategory1" AppendDataBoundItems="True" runat="server" >
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
My code behind:
protected void gv_RowEditing(object sender, GridViewEditEventArgs e)
{
gv_table1.EditIndex = e.NewEditIndex;
DropDownList drpcategory1 = ((DropDownList)gv_table1.Rows[e.NewEditIndex].Cells[8].FindControl("drpcategory1"));
//BindDropDown(drpcategory1);
dt = con.GetData("Select category_name from category");
String str = gv_table1.Rows[e.NewEditIndex].FindControl("drpcategory1").GetType().ToString();
//((DropDownList)gv_table1.Rows[e.NewEditIndex].Cells[8].FindControl("drpcategory1")).DataSource = dt;
drpcategory1.DataSource = dt;
drpcategory1.DataTextField = "category_name";
drpcategory1.DataValueField = "category_name";
drpcategory1.DataBind();
this.setgrid();
}
I've tried looking on the net and tried many things in vain. I am new to asp. Thanks in advance. I would like the dropdown to be bound only when user enters edit mode.
Code Behind: Tested Code and also set dropdown-list selected value on edit mode
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList ddList= (DropDownList)e.Row.FindControl("drpcategory1");
//bind dropdown-list
DataTable dt = con.GetData("Select category_name from category");
ddList.DataSource = dt;
ddList.DataTextField = "category_name";
ddList.DataValueField = "category_name";
ddList.DataBind();
DataRowView dr = e.Row.DataItem as DataRowView;
//ddList.SelectedItem.Text = dr["category_name"].ToString();
ddList.SelectedValue = dr["category_name"].ToString();
}
}
}
protected void gv_RowEditing(object sender, GridViewEditEventArgs e)
{
gv.EditIndex = e.NewEditIndex;
gridviewBind();// your gridview binding function
}
I do it like this. In which, Name and Id are two fields of Company object:
HTML Code:
<asp:TemplateField HeaderText="Công ty">
<EditItemTemplate>
<asp:DropDownList ID="ddlCompanyEdit" DataSource="<%# PopulateddlCompanyEdit() %>" DataValueField="Id" DataTextField="Name" runat="server"></asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lbCompany" runat="server" Text='<%#Bind("Company") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
C# code behind:
protected IEnumerable<Company> PopulateddlCompanyEdit()
{
using (var bkDb = new BrickKilnDb())
{
return bkDb.Companies.ToList();
}
}
protected void gvProject_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
string Active = "";
if (e.Row.DataItem != null)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
Label lblEditActive = (Label)e.Row.FindControl("lblUP_ET_ActiveStatus");
if (lblEditActive.Text != string.Empty)
{
Active = lblEditActive.Text.Trim();
}
DropDownList ddlActive = (DropDownList)e.Row.FindControl("ddlUP_ET_ActiveStatus");
ddlActive.Items.Clear();
ddlActive.Items.Add("True");
ddlActive.Items.Add("False");
ddlActive.DataBind();
ddlActive.Items.FindByText(Active).Selected = true;
}
}
}
catch (Exception ex)
{
throw ex;
}
}
The event RowEditing occurs just before a row is edited.
You should use the RowDataBound event instead.
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (gv.EditIndex == e.Row.RowIndex &&
e.Row.RowType==DataControlRowType.DataRow)
{
DropDownList drpcategory1 = (DropDownList)e.Row.FindControl("drpcategory1");
//bind the control
}
}
You have to use RowDataBound event to bind the dropdown control for edited row. Please use below method in RowDataBound event.
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowState == DataControlRowState.Edit)
{
DropDownList drpcategory1 = (DropDownList)e.Row.FindControl("drpcategory1");
DataTable dt = con.GetData("Select category_name from category");
drpcategory1.DataSource = dt;
drpcategory1.DataTextField = "category_name";
drpcategory1.DataValueField = "category_name";
drpcategory1.DataBind();
}
}
Hope this will help you.

Categories

Resources