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.
Related
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();
}
}
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;
}
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
I could not properly bind my child repeater (lvTwo) using a datatable. It always throws a NullReferenceException. On debug mode, my datatable looked fine, any thoughts?
HTML Code:
<asp:Repeater ID="lvOne" runat="server" OnItemDataBound="lvOne_ItemDataBound">
<ItemTemplate>
<div>
I am the one.
</div>
<asp:Repeater ID="lvTwo" runat="server">
<ItemTemplate>
I am the two.
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:Repeater>
Code-behind (dtTable to bind for lvOne, dtTable2 to bind for lvTwo):
protected void Page_Load(object sender, EventArgs e)
{
DataTable dtTable = new DataTable();
dtTable.TableName = "T1";
dtTable.Columns.Add("ProjectName");
DataRow dr = dtTable.NewRow();
dr["ProjectName"] = "ThreeSixFive";
dtTable.Rows.Add(dr);
if (!Page.IsPostBack)
{
lvOne.DataSource = dtTable;
lvOne.DataBind();
}
}
protected void lvOne_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
DataTable dtTable2 = new DataTable();
dtTable2.TableName = "T2";
dtTable2.Columns.Add("C");
DataRow dr = dtTable2.NewRow();
dr["C"] = "ThreeSixFive";
dtTable2.Rows.Add(dr);
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
if (dtTable2 != null)
{
lvTwo.DataSource = dtTable2;
lvTwo.DataBind();
}
}
}`
The culprit was due to the unrecognized lvTwo control. It was able to compile due to the control being registered in the designer file, instead I need to use the ff:
var lvTwo = (ListView) e.Item.FindControl("lvTwo");
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();
}
}