Binding issues with GridView in ASP.NET - asp.net

I am totally confused with the way ASP.NET GridView binding works.
I have a GridView. Now, on the page load (using !IsPostBack) I am binding the GridView.
My gridview has an edit button. When I click on it, the GridView becomes blank. Behaviour could be expected, because when I click on the edit button, a postback happens and, because I have binded the GridView inside the !IsPostback condition, it won't bind the GridView.
Now, if I remove the GridView binding, and place it outside the !IsPostback condition, the edit button works. But, I am unable to get the edited value from the TextBox. In this case, too, the behaviour could be expected, as when the update button is clicked, the GridView is re-binded, because the binding this time has been done outside the !IsPostback condition.
So, I want to know what could be the proper code for the edit button to work, and at the same time, the edited values from the TextBox could be retrieved.
Question Updated with Code:
<asp:GridView ID="grdExternalLinkSection1" ShowFooter="true" runat="server" Width="100%" AutoGenerateColumns="false" CellPadding="5" EnableViewState="true">
<EmptyDataTemplate>
External Link Title
<asp:TextBox ID="txtExternalLinkTitleEmptySection1" runat="server"></asp:TextBox>
External Link Url
<asp:TextBox ID="txtExternalLinkUrlEmptySection1" runat="server"></asp:TextBox>
<asp:Button ID="btnExternalLinkEmptySection1" OnCommand="grdExternalLinkSection_Button_Clicks" runat="server" Text="Add" CommandName="headernew,1" style="padding:3px; width:56px;" />
</EmptyDataTemplate>
<Columns>
<asp:TemplateField HeaderText="Title">
<ItemTemplate>
<asp:Label ID="lblExternalLinkTitleSection1" runat="server"><%# Eval("Title") %></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtExternalLinkTitleEditSection1" runat="server" Text='<%# Bind("Title") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtExternalLinkTitleFooterSection1" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Url">
<ItemTemplate>
<asp:Label ID="lblExternalLinkUrlSection1" runat="server"><%# Eval("Url")%></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtExternalLinkUrlEditSection1" runat="server" Text='<%# Bind("Url") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtExternalLinkUrlFooterSection1" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Manage">
<ItemTemplate>
<asp:Button ID="btnExternalLinkEditSection1" OnCommand="grdExternalLinkSection_Button_Clicks" runat="server" CommandName="Editing,1" CommandArgument='<%# Container.DataItemIndex %>' Text="Edit" />
<asp:Button ID="btnExternalLinkDeleteSection1" OnCommand="grdExternalLinkSection_Button_Clicks" runat="server" CommandName="Deleting,1" CommandArgument='<%# Container.DataItemIndex %>' Text="Delete" />
</ItemTemplate>
<EditItemTemplate>
<asp:Button ID="btnExternalLinkUpdateSection1" OnCommand="grdExternalLinkSection_Button_Clicks" runat="server" CommandName="Updating,1" CommandArgument='<%# Container.DataItemIndex %>' Text="Update" />
<asp:Button ID="btnExternalLinkCancelSection1" OnCommand="grdExternalLinkSection_Button_Clicks" runat="server" CommandName="Canceling,1" CommandArgument='<%# Container.DataItemIndex %>' Text="Cancel" />
</EditItemTemplate>
<FooterTemplate>
<asp:Button ID="btnExternalLinkAddFooterSection1" OnCommand="grdExternalLinkSection_Button_Clicks" runat="server" CommandName="Footer,1" Text="Add" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
below is the function which does the binding work:
GridView grid;
protected void BindExternalLinks(int SectionID, string ControlName)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlDataAdapter adapter = new SqlDataAdapter("user_Newsletter_GetExternalLinks", connection))
{
adapter.SelectCommand.CommandType = CommandType.StoredProcedure;
adapter.SelectCommand.Parameters.Add("#SectionID", SqlDbType.Int).Value = SectionID;
adapter.SelectCommand.Parameters.Add("#PortalID", SqlDbType.Int).Value = PortalID;
DataTable dt = new DataTable();
adapter.Fill(dt);
grid = (GridView)this.FindControl(ControlName);
grid.DataSource = dt;
}
}
}
protected void BindAllExternalLinks()
{
for (int i = 1; i <= NewsLetterSectionCount; i++)
{
BindExternalLinks(i, "grdExternalLinkSection" + i);
grid.DataBind();
}
}
below is my PageLoad:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindAllExternalLinks();
}
}
and below is my command buttons event: i have kept the handler common for all command buttons:
protected void grdExternalLinkSection_Button_Clicks(object sender, CommandEventArgs e)
{
int rowIndex = (e.CommandArgument != "") ? Convert.ToInt32(e.CommandArgument) : -1;
string[] commandNames = e.CommandName.ToString().Split(',');
string command = commandNames[0].ToString().ToLower();
int sectionID = Convert.ToInt32(commandNames[1]);
GridView grid = (GridView)this.FindControl("grdExternalLinkSection" + sectionID);
try
{
if (command == "headernew")
{
TextBox title = grid.Controls[0].Controls[0].FindControl("txtExternalLinkTitleEmptySection" + sectionID) as TextBox;
TextBox url = grid.Controls[0].Controls[0].FindControl("txtExternalLinkUrlEmptySection" + sectionID) as TextBox;
UpdateExternalLinks(ModifyExternalLinks.Insert, sectionID, title.Text, url.Text);
MessageShow("External Link Added Successfully");
}
else if (command == "editing")
{
//grid.EditIndex = rowIndex;
}
else if (command == "canceling")
{
grid.EditIndex = -1;
}
else if (command == "footer")
{
Response.Write("Inside Footer");
}
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
BindExternalLinks(sectionID, "grdExternalLinkSection" + sectionID);
grid.DataBind(); //here i am binding once the records are modified.
}

You are almost there. BindAllExternalLinks() should be inside the if (!IsPostback) block, correct.
The additional thing you should do is to rebind the grid after you have done your editing:
else if (command == "editing")
{
// do your update stuff here
BindAllExternalLinks();
}

Just rebind the gridview under each postback event(). Even if you bind it to an object datasource or SQL DataSource, you have to call the databind method after every postback request like
MyGridview.DataBind();
UpdatePanel1.Update();

Related

asp.net editable gridview "no data found" row causes issue after postback

I have a simple problem with my gridview. It is an editable gridview which allows inserting, updating and deleting rows. It is bound to a datatable. I store the datatable in the viewstate and bind the datatable on page_load for every postback. There is no column order or paging and I only have a few records on this gridview. When there is no data to display, I add an empty message text like "no data found" manually to grid. It is okey for the first page_load. But after postback, this text disappears, but the row is still there. And the main problem is the row has "edit" and "delete" command columns after postback. This row should not have edit or delete columns after postback. It works really fine before postback.
This problem never happens if there is at least one row in gridview.
If I have at least one row, then if I add more rows: No problem
If I have the empty grid, then I add a row (before any postback for example combobox value change): No problem
If I have the empty grid: then I do a postback by changing a value in a combobox, then "no rows found" message in the grid disappearing and there is an extra row in the grid which has no text and has edit and delete columns
If I have the grid with that unwanted row, then I add a row to that gridview: The unwanted row is going away and new row appearing on the grid. No problem
So the only problem is that extra row which is appearing after postback.
Code details are below. Please help me with this silly problem. I couldnt solve it for days.
ASPX:
<asp:GridView ID="grdTerminals" runat="server"
AutoGenerateColumns="False" DataKeyNames="TRM_ID"
OnRowCancelingEdit="grdTerminals_RowCancelingEdit"
OnRowDataBound="grdTerminals_RowDataBound"
OnRowEditing="grdTerminals_RowEditing"
OnRowUpdating="grdTerminals_RowUpdating" ShowFooter="True"
OnRowCommand="grdTerminals_RowCommand"
OnRowDeleting="grdTerminals_RowDeleting"
HeaderStyle-BackColor="#73be1e" HeaderStyle-ForeColor="Window" HeaderStyle-Font-Bold="true" Width="500px" HeaderStyle-Height="30">
<Columns>
<asp:TemplateField HeaderText="Terminal" HeaderStyle-HorizontalAlign="Left">
<EditItemTemplate>
<asp:DropDownList ID="ddlTerminal" runat="server" DataTextField="TRM_MNMC" DataValueField="TRM_ID">
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblTerminal" runat="server" Text='<%# Eval("TRM_MNMC") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlNewTerminal" runat="server" DataTextField="TRM_MNMC" DataValueField="TRM_ID">
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="TAS No" HeaderStyle-HorizontalAlign="Left">
<EditItemTemplate>
<asp:TextBox ID="txtTASNo" runat="server" Text='<%# Bind("TAS_NO") %>' Width="120"></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNewTASNo" runat="server" Width="120"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblTASNo" runat="server" Text='<%# Bind("TAS_NO") %>' Width="120"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="" ShowHeader="False">
<EditItemTemplate>
<asp:LinkButton ID="lbkUpdate" runat="server" CausesValidation="True" CommandName="Update" Text="Kaydet"></asp:LinkButton>
<asp:LinkButton ID="lnkCancel" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="lnkAdd" runat="server" CausesValidation="False" CommandName="Insert" Text="Insert"></asp:LinkButton>
</FooterTemplate>
<ItemTemplate>
<asp:LinkButton ID="lnkEdit" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="" ShowDeleteButton="True" ShowHeader="True" DeleteText="Delete"/>
</Columns>
</asp:GridView>
C#
// I am storing the data in ViewState
DataTable dtTerminals
{
get
{
return ViewState["_dtVehicleTerminals"] as DataTable;
}
set
{
ViewState["_dtVehicleTerminals"] = value;
}
}
//Page Load
protected void Page_Load(object sender, EventArgs e)
{
if (dtTerminals == null)
{
dtTerminals = new DataTable();
dtTerminals.Columns.Add("TRM_ID");
dtTerminals.Columns.Add("TRM_MNMC");
dtTerminals.Columns.Add("TAS_NO");
}
if (!IsPostBack)
{
string VhcId = Request["vhc_id"];//Edit mode
if (!string.IsNullOrEmpty(VhcId))
{
BindTerminalInfo(VhcId);
}
else
{
//To show empty grid
BindTerminalGrid();
}
}
// Bind Terminal Info
void BindTerminalInfo(string VhcId)
{
dtTerminals = VehicleManager.GetVehicleTerminals(VhcId);
BindTerminalGrid();
}
//Bind Terminal Grid
public void BindTerminalGrid()
{
if (dtTerminals.Rows.Count > 0)
{
grdTerminals.DataSource = dtTerminals;
grdTerminals.DataBind();
}
else
{
//Show No Records Found
dtTerminals.Rows.Add(dtTerminals.NewRow());
grdTerminals.DataSource = dtTerminals;
grdTerminals.DataBind();
grdTerminals.Rows[0].Cells.Clear();
grdTerminals.Rows[0].Cells.Add(new TableCell());
grdTerminals.Rows[0].Cells[0].Text = "No Data found";
dtTerminals.Rows.Clear();
}
}
//Other methods related to grid functionality
protected void grdTerminals_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddlTerminal = (DropDownList)e.Row.FindControl("ddlTerminal");
if (ddlTerminal != null)
{
ddlTerminal.DataSource = VehicleManager.GetDefaultUserTerminalNames();
ddlTerminal.DataBind();
ddlTerminal.DataTextField = "TRM_MNMC";
ddlTerminal.DataValueField = "TRM_ID";
ddlTerminal.SelectedValue = grdTerminals.DataKeys[e.Row.RowIndex].Values[0].ToString();
}
}
if (e.Row.RowType == DataControlRowType.Footer)
{
DropDownList ddlNewTerminal = (DropDownList)e.Row.FindControl("ddlNewTerminal");
ddlNewTerminal.DataSource = VehicleManager.GetDefaultUserTerminalNames();
ddlNewTerminal.DataBind();
}
}
protected void grdTerminals_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
grdTerminals.EditIndex = -1;
BindTerminalGrid();
}
protected void grdTerminals_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
Label lblId = (Label)grdTerminals.Rows[e.RowIndex].FindControl("lblTrmUnqId");
DropDownList ddlTerminal = (DropDownList)grdTerminals.Rows[e.RowIndex].FindControl("ddlTerminal");
TextBox txtTASNo = (TextBox)grdTerminals.Rows[e.RowIndex].FindControl("txtTASNo");
dtTerminals.Rows[e.RowIndex]["TRM_ID"] = ddlTerminal.SelectedValue;
dtTerminals.Rows[e.RowIndex]["TRM_MNMC"] = ddlTerminal.SelectedItem;
dtTerminals.Rows[e.RowIndex]["TAS_NO"] = txtTASNo.Text;
grdTerminals.EditIndex = -1;
BindTerminalGrid();
}
protected void grdTerminals_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string TrmId = Convert.ToString(grdTerminals.DataKeys[e.RowIndex].Values[0]);
dtTerminals.Rows.Remove(dtTerminals.Rows[e.RowIndex]);
BindTerminalGrid();
}
protected void grdTerminals_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("Insert"))
{
DropDownList ddlNewTerminal = (DropDownList)grdTerminals.FooterRow.FindControl("ddlNewTerminal");
TextBox txtTASNo = (TextBox)grdTerminals.FooterRow.FindControl("txtNewTASNo");
DataRow dr = dtTerminals.NewRow();
dr["TRM_ID"] = ddlNewTerminal.SelectedValue;
dr["TRM_MNMC"] = ddlNewTerminal.SelectedItem.Text;
dr["TAS_NO"] = txtTASNo.Text;
dtTerminals.Rows.Add(dr);
BindTerminalGrid();
}
}
protected void grdTerminals_RowEditing(object sender, GridViewEditEventArgs e)
{
grdTerminals.EditIndex = e.NewEditIndex;
BindTerminalGrid();
}
I am not sure it is the correct solution . But try adding Empty data text property of Gridview.
<asp:gridview id="CustomersGridView"
datasourceid="CustomersSqlDataSource"
autogeneratecolumns="true"
emptydatatext="No data in the data source."
runat="server">
<emptydatarowstyle backcolor="LightBlue"
forecolor="Red"/>
</asp:gridview>
Or try like this
<asp:TemplateField>
<EditItemTemplate>
<asp:ImageButton ID="imgBtnUpdate" runat="server" Height="32px"
ImageUrl="~/Images/Update.jpg" ToolTip="Update" Width="32px" CommandName="Update"/>
<asp:ImageButton ID="imgBtnDelete" runat="server" Height="32px"
ImageUrl="~/Images/delete.gif" style="margin-left: 0px" ToolTip="Delete"
Width="32px" CommandName="Delete"/>
<asp:ImageButton ID="imgBtnCancel" runat="server" Height="32px"
ImageUrl="~/Images/Cancel.png" ToolTip="Cancel" Width="32px" CommandName="Cancel"/>
</EditItemTemplate>
<FooterTemplate>
<asp:ImageButton ID="btnAdd" runat="server" ImageUrl="~/Images/AddNew.gif"
ToolTip="Add New Record" CommandName="Add"/>
</FooterTemplate>
<ItemTemplate>
<asp:ImageButton ID="imgBtnEdit" runat="server" Height="32px"
ImageUrl="~/Images/pencil.png" ToolTip="Edit" Width="32px" CommandName="Edit"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<EditItemTemplate>
<asp:TextBox ID="txtName" runat="server" Text='<%# Eval("name") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNameFooter" runat="server"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Eval("name") %>'></asp:Label>
</ItemTemplate>
Finally I have fixed this problem. The solution is adding
if (!Request.Form["__EVENTTARGET"].Split('$').Contains(grdTerminals.ID))
{
BindTerminalGrid();
}
code block to If(Postback) statement. I should rebind data for everypostback but only if the control which caused postback is not the "datagrid".

Binding foreign key after update in asp gridview with entity framework 3.5

I have been trying to solve the issues for a while. When you create databinding with a foreign key in asp gridview, then you edit a row and change the foreign key in a dropbox for instance, save changes and return back to the view mode (edit row = -1), the value in the foreign key column dissapears (unless it was not changed). However, if you refresh the page (without sending the data again) the value is shown properly, changed as expected.
This also happens in the SPGridView (sharepoint grid view) which inherits from the asp grid view.
Let me show you a very simplified example with update method only:
(I hope it is not too simplified)
The grid
<asp:GridView
ID="exampleGridView"
runat="server"
DataKeyNames="Id"
AutoGenerateColumns="false"
OnRowUpdating="UpdateClick"
OnRowDataBound="RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Id">
<ItemTemplate>
<asp:Label ID="Id" runat="server" Text='<%# Bind("Id") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Login">
<ItemTemplate>
<asp:Label ID="Login" runat="server" Text='<%# Bind("Login") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="EditLoginTextBox" runat="server" Text='<%# Bind("Login") %>' Enabled="false" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Role">
<ItemTemplate>
<asp:Label ID="Role" runat="server" Text='<%# Bind("Role.Title") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="EditRoleDropDownList" runat="server" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:LinkButton ID="EditLinkBtn" runat="server" CommandName="Edit" Text="edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="UpdateLinkBtn" runat="server" CommandName="Update" Text="update" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The code behind
protected void UpdateClick(object sender, System.Web.UI.WebControls.GridViewUpdateEventArgs e)
{
// context taken from constructor, created at the beginning of a request and disposed at the end of a request
User user = this.ctx.Users.First(u => u.Id == id);
GridViewRow row = this.exampleGridView.Rows[e.RowIndex];
user.Login = ((TextBox)row.FindControl("EditLoginTextBox")).Text;
int roleId =int.Parse(((DropDownList)row.FindControl("EditRoleDropDownList")).SelectedValue);
if (user.Role.Id != roleId)
{
user.Role = ctx.Attach(new Role
{
Id = roleId
});
}
this.ctx.SaveChanges();
this.exampleGridView.EditIndex = -1;
this.BindGrid();
}
protected void RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow &&
(e.Row.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
{
var user = (User)e.Row.DataItem;
var editRoleDropDownList = (DropDownList)e.Row.FindControl("EditRoleDropDownList");
this.BindRoleDropDownList(editRoleDropDownList);
editRoleDropDownList.SelectedValue = user.Role.Id.ToString();
}
}
private void BindGrid()
{
this.exampleGridView.DataSource = this.ctx.Users.Include(u => u.Role);
this.exampleGridView.DataBind();
}
private void BindRoleDropDownList(DropDownList roleDropDownList)
{
// list of roles
if (this.cachedRoles == null)
{
this.cachedRoles = this.ctx.Roles.ToList();
}
roleDropDownList.DataSource = this.cachedRoles;
roleDropDownList.DataValueField = "Id";
roleDropDownList.DataTextField = "Name";
roleDropDownList.DataBind();
}
The answer is simpler than I thought. The proble is in the Update method:
int roleId = int.Parse(((DropDownList)row.FindControl("EditRoleDropDownList")).SelectedValue);
if (user.Role.Id != roleId)
{
// this is the problem
user.Role = ctx.Attach(new Role
{
Id = roleId
});
}
The problem is that I overwrite the role with this new object which has Role.Title equal to empty string obviously. And the object stays there. So the proper solution is following:
int roleId = int.Parse(((DropDownList)row.FindControl("EditRoleDropDownList")).SelectedValue);
if (user.Role.Id != roleId)
{
user.Role = this.ctx.Roles.First(r => r.Id == roleId);
}

How to find Grid view button click event?

Button btnAddrecord = (Button)sender;
GridViewRow gvr =(GridViewRow)btnAddrecord.NamingContainer;
if (btnAddrecord.CommandName == "onAddMaterial")
Define the button in your grid view markup and assign a CommandName value to the button, like this:
<asp:GridView ID="GridView1" AutoGenerateColumns="False" runat="server"
OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Add Record">
<ItemTemplate>
<asp:Button ID="btnAddRecord"
CommandArgument="<%# ((GridViewRow)Container).RowIndex %>"
CommandName="AddRecord" runat="server" Text="Add" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Now in your code-behind, you can handle the OnRowCommand event and AddRecord command, like this:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "AddRecord")
{
// Get index of row passed as command argument
int index = Convert.ToInt32(e.CommandArgument.ToString());
// Your logic here
}
}
1.Give a command name for button..
2.Then inside gridview
if e.commandname="yourcommandname"
{
//your code..
}
<!--We use onrowcommand for getting the selected row -->
<asp:GridView runat="server" ID="gvTest" AutoGenerateColumns="False" OnRowCommand="gvTest_OnRowCommand" >
<Columns>
<asp:TemplateField HeaderText="BookId" >
<ItemTemplate>
<asp:Label runat="server" ID="lblBookId" Text='<%# Bind("[BookId]") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtBookId" Text='<%# Bind("[BookId]") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:TemplateField>
<asp:TemplateField HeaderText="Options">
<ItemTemplate>
<asp:Button runat="server" ID="btnDelete" CommandArgument="<%# Container.DisplayIndex %>" CommandName="IsDelete" Text="Delete"></asp:Button>
</ItemTemplate>
</asp:TemplateField>
//Code Behind
protected void gvTest_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
//getting rowindex which we have selected by using CommandArgument
int rowindex = Convert.ToInt32(e.CommandArgument);
if (e.CommandName == "IsDelete")
{
int bkid = gvTest.Rows[rowindex].Cells[0].FindControl("BookId");
//call a method to delete book using the bkid
}
}
catch (Exception ex)
{
Response.Write(ex);
}
}

ASP.NET C# - Refresh 2nd DropdownList based on select of 1st dropdownlist

I am new to ASP.NET
I have this code Page1.aspx for the DetailsView:
<InsertItemTemplate>
<asp:DropDownList id="VendorName" datasourceid="VendorSqlDataSource"
datatextfield="VendorName" DataValueField="VendorID"
SelectedValue='<%# Bind("VendorID") %>' runat="server" AutoPostBack="true" />
</InsertItemTemplate>
<EditItemTemplate>
<asp:DropDownList id="VendorName" datasourceid="VendorSqlDataSource"
datatextfield="VendorName" DataValueField="VendorID"
SelectedValue='<%# Bind("VendorID") %>' runat="server" OnSelectedIndexChanged="dllVendor_OnSelectedIndexChanged" AutoPostBack="true" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Vendor BU">
<ItemTemplate>
<asp:Label ID="VendorBUName" runat="Server" style="text-align:left; width:100%" Text='<%# Eval("VendorBUName")%>' Width="70%"/>
</ItemTemplate>
<InsertItemTemplate>
<asp:DropDownList id="VendorBUName" datasourceid="VendorBUSqlDataSource"
datatextfield="VendorBUName" DataValueField="VendorBUID"
SelectedValue='<%# Bind("VendorBUID") %>' runat="server"/>
</InsertItemTemplate>
<EditItemTemplate>
<asp:DropDownList id="VendorBUName" datasourceid="VendorBUSqlDataSource"
datatextfield="VendorBUName" DataValueField="VendorBUID"
SelectedValue='<%# Bind("VendorBUID") %>' runat="server"/>
</EditItemTemplate>
</asp:TemplateField>
I am trying to make the code behind Page1.aspx.cs to refresh the 2nd Dropdown List in this code behind:
(VendorBUName"), but keeps getting a error "".
protected void OnSelectedIndexChanged(object VendorID)
{
string queryString = "SELECT VendorBUID, VendorBUName From MDF_VendorBU WHERE VendorID = #VendorID";
System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection("ConnectionString");
System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand(queryString, connection);
command.Parameters.AddWithValue("#VendorID", VendorID);
connection.Open();
DataTable dt = new DataTable();
SqlDataAdapter ad = new SqlDataAdapter(command);
ad.Fill(dt);
/*
VendorBUName.Items.Clear();
if (dt.Rows.Count > 0)
{
VendorBUName.DataSource = dt;
VendorBUName.DataTextField = "VendorBUName";
VendorBUName.DataValueField = "VendorBUID";
VendorBUName.DataBind();
}
*/
connection.Close();
}
//protected void dllVendor_OnSelectedIndexChanged(object sender, System.EventArgs e)
//{
//OnSelectedIndexChanged(VendorName.SelectedValue.ToString());
//}
I am keep getting the "The name 'VendorBUName' does not exist in the current context", looks like code behind is not recognize the 2nd dropdownlist in the Page1.aspx
Please help.
I would try to use a FindControl call here since you have a label AND a combo box both with the same name.
So in OnSelectedIndexChanged do something like
var control = (DropDownList) yourDetailsView.FindControl("VendorBUName");
if(control!=null)
{
//do your stuff on the drop down
}

Asp.Net set Visibility of Dropdown list inside gridview in aTemplate Field

I have a Gridview with Template field
<asp:TemplateField HeaderText="Scoring">
<ItemTemplate>
<asp:DropDownList ID="ddlY_N_NA" runat="server"
Visible='<%#Eval("IsTextBox")%>' ></asp:DropDownList>
<asp:TextBox ID="txtAudit" runat="server"
Visible='<%#Eval("IsTextBox")%>' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
I need to set the visibility of drop down based on the visibility of Textbox.
Either of the two has to be shown per row but not both.
Can any help me in this.
Thanks in advance.
Try the following:
<asp:TemplateField HeaderText="Scoring">
<ItemTemplate>
<asp:DropDownList ID="ddlY_N_NA" runat="server"
Visible='<%# ((bool)Eval("IsTextBox")) ? "false" : "true" %>' >
</asp:DropDownList>
<asp:TextBox ID="txtAudit" runat="server"
Visible='<%#Eval("IsTextBox")%>' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
You can do it with the RowDataBound event of the Gridview.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRow dr = ((DataRowView)e.Row.DataItem).Row;
if (dr["ColumnName"].ToString()) // your Condition
{
((DropDownList)e.Row.FindControl("dropdownID")).Visible = false;
}
else if (dr["ColumnName"].ToString()) // your Condition
{
((TextBox)e.Row.FindControl("TextboxID")).Visible = false;
}
}
}
Hi, Akram Shahda below is my solution
<asp:TemplateField HeaderText="Scoring" HeaderStyle-Width="12%">
<ItemTemplate>
<asp:DropDownList ID="ddlY_N_NA" Visible='<%#SetVisibility(DataBinder.Eval(Container.DataItem,"IsTextBox"))%>'
runat="server" CssClass="Qdropdown">
</asp:DropDownList>
<asp:TextBox onkeypress="return isNumberKey(event);" ID="txtAudit" Visible='<%#Convert.ToBoolean(Eval("IsTextBox"))%>'
MaxLength="10" runat="server" CssClass="Qinputbox" Width="54px" ValidationGroup="txt"></asp:TextBox>
<asp:HiddenField ID="hdnTextBoxCondition" Value='<%#SetTextBoxVisibility(Eval("IsTextBox"),Eval("TextBoxConditions"))%>'
Visible='<%#Eval("IsTextBox")%>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
In the code behind I have written the methods which will set the visibility
public bool SetVisibility(object value)
{
if (Convert.ToBoolean(value))
return false;
else
return true;
}
public string SetTextBoxVisibility(object value, object condition)
{
if (Convert.ToBoolean(value))
return Convert.ToString(condition);
else
return "";
}

Resources