I've spent all afternoon trying to do this using CODE BEHIND without success so I am asking for some C# code.
Basically, I have a GV and a DV in a master/detail relationship. GV displays ID and Name. If I click Select on a GV row, I want to see its ID, Name and Address in DV. I know how get this to work declaratively in an aspx file. But in C# code behind, I don't know how to proceed at this function:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("Select"))
{
// PLEASE GIVE ME THE CODE HERE TO BIND THE DETAILSVIEW. THANKS!
// I am using a sqldatasource if it makes any difference
}
}
Here's a general solution showing you how to achieve this, please note that this solution isn't extremely error-safe but I suppose you'll get the jist of it. Please comment if there's anything unclear.
Code-behind:
protected void gv_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
GridViewRow selected = gv.Rows[Convert.ToInt32(e.CommandArgument)];
List<ThatClass> cList = new List<ThatClass>();
cList.Add(new ThatClass(selected.Cells[0].Text, selected.Cells[1].Text));
dv.DataSource = cList;
dv.DataBind();
}
}
Markup:
<asp:GridView ID="gv" runat="server" AutoGenerateColumns="false" OnRowCommand="gv_RowCommand">
<Columns>
<asp:BoundField DataField="A" HeaderText="A"/>
<asp:BoundField DataField="B" HeaderText="B" />
<asp:CommandField ShowSelectButton="true" />
</Columns>
</asp:GridView>
<asp:DetailsView runat="server" ID="dv">
</asp:DetailsView>
FYI: I bound the GV using a List:
protected void Page_Load(object sender, EventArgs e)
{
List<ThatClass> cList = new List<ThatClass>();
cList.Add(new ThatClass("123", "abc"));
cList.Add(new ThatClass("456", "def"));
gv.DataSource = cList;
gv.DataBind();
}
Related
while updating gridview record . old values only getting updated. im using bound field. getting old value while im fetching data in variable.
<asp:GridView runat="server" ID="GvLeads" AutoGenerateColumns="false" AutoGenerateEditButton="true" AutoGenerateDeleteButton="true" OnRowDeleting="GvLeads_RowDeleting" OnRowEditing="GvLeads_RowEditing" OnRowCancelingEdit="GvLeads_RowCancelingEdit" EmptyDataText="No Records Found" OnRowUpdating="GvLeads_RowUpdating" OnRowDeleted="GvLeads_RowDeleted">
<Columns>
<asp:BoundField HeaderText="Id" DataField="LeadId" />
<asp:BoundField HeaderText="Company" DataField="Companyname" />
</Columns>
</GridView >
code behind
protected void GvLeads_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = GvLeads.Rows[e.RowIndex];
String str = ((TextBox)(row.Cells[1].Controls[0])).Text;
int Leadid = Convert.ToInt32(str);
string CompanyName = ((TextBox)(row.Cells[2].Controls[0])).Text;
}
This usually happens when you are populating grid at Page_Load as soon as RowUpdating event gets called before that Page_Load event get's called which populates the grid with initial values. How to Avoid? Use !IsPostBack for this purpose
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid(); // For e.g.
}
}
i have allowed paging and added the below codes but got the error. Does anyone know what could be the problem?
Code:
protected void SubmitAppraisalGrid_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
SubmitAppraisalGrid.PageIndex = e.NewSelectedIndex;
SubmitAppraisalGrid.DataBind();
}
Design:
<asp:GridView ID="SubmitAppraisalGrid" runat="server"
AutoGenerateColumns="False" BorderWidth="0px"
onrowcreated="SubmitAppraisalGrid_RowCreated" ShowHeader="False"
style="margin-right: 0px" AllowPaging="True" PageSize="1"
onselectedindexchanging="SubmitAppraisalGrid_SelectedIndexChanging">
</asp:GridView>
If you have set a gridviews AllowPaging attribute to “true” and do not handle the PageIndexChanging event then this error raise.
To work with paging add the PageIndexChanging event handler to grid and change your markup and code as:
<asp:GridView ID="SubmitAppraisalGrid" runat="server"
AutoGenerateColumns="False" BorderWidth="0px"
onrowcreated="SubmitAppraisalGrid_RowCreated" ShowHeader="False"
style="margin-right: 0px" AllowPaging="True" PageSize="1"
onselectedindexchanging="SubmitAppraisalGrid_SelectedIndexChanging"
OnPageIndexChanging="SubmitAppraisalGrid_PageIndexChanging">
</asp:GridView>
///
protected void gvList_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
SubmitAppraisalGrid.PageIndex = e.NewPageIndex;
SubmitAppraisalGrid.DataBind();
//bindGrid();
//SubmitAppraisalGrid.PageIndex = e.NewPageIndex;
//SubmitAppraisalGrid.DataBind();
}
protected void SubmitAppraisalGrid_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
/// you selected index related logic here.
}
This event is not raised when you programmatically set the PageIndex property.
Check MSDN documentation of GridView.PageIndexChanging Event
For reference:
The GridView fired event PageIndexChanging which wasn't handled
Your code should be inside On PageIndexChanging Event
protected void SubmitAppraisalGrid_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
SubmitAppraisalGrid.PageIndex = e.NewPageIndex;
SubmitAppraisalGrid.DataBind();
}
Design:
<asp:GridView ID="SubmitAppraisalGrid" runat="server"
AutoGenerateColumns="False" BorderWidth="0px"
onrowcreated="SubmitAppraisalGrid_RowCreated" ShowHeader="False"
style="margin-right: 0px" AllowPaging="True" PageSize="1"
OnPageIndexChanging="SubmitAppraisalGrid_PageIndexChanging">
</asp:GridView>
try
OnPageIndexChanging="SubmitAppraisalGrid_PageIndexChanging"
instead of
onselectedindexchanging="SubmitAppraisalGrid_SelectedIndexChanging"
protected void SubmitAppraisalGrid_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
SubmitAppraisalGrid.PageIndex = e.NewPageIndex;
BindGrid();
}
insted of using
SubmitAppraisalGrid.PageIndex = e.NewSelectedIndex;
you must use
SubmitAppraisalGrid.PageIndex = e.NewPageIndex;
and if you got error again plese post the error too..
Step by Step:
Select gridview from design and go to property and fire the event (PageIndexChanging)
Code : gridviewname.pageindex=e.NewPageIndex;
You need to call the Pageindex changing event from selected index changing event of dropdown.
protected void PageDropDownList_SelectedIndexChanged(Object sender, EventArgs e)
{
// Retrieve the pager row.
GridViewRow pagerRow = SubmitAppraisalGrid.BottomPagerRow;
// Retrieve the PageDropDownList DropDownList from the bottom pager row.
DropDownList pageList = (DropDownList)pagerRow.Cells[0].FindControl("PageDropDownList");
// Set the PageIndex property to display that page selected by the user.
GridViewPageEventArgs evt = new GridViewPageEventArgs(pageList.SelectedIndex);
SubmitAppraisalGrid_PageIndexChanging(sender, evt);
}
I am using a GridView that has many rows with the same values, so I grouped these rows using GridViewHelper class. Now I want to put a separate line between each grouping values. How to do that?
The following snapshot shows you the current situation:
I wasn't sure if you wanted to style them when rendered or when you click the row. So here is both. You can decide what styles you want. :-)
Set the appropriate attributes in your ASP.NET GridView control for controlling CSS:
<asp:GridView ID="gridviewid"
runat="server"
CssClass="gridview"
AutoGenerateSelectButton="True"
GridLines="None"
AllowPaging="true"
PageSize="10">
<HeaderStyle CssClass="gridViewHeader" />
<RowStyle CssClass="gridViewRow" />
<AlternatingRowStyle CssClass="gridViewAltRow" />
<SelectedRowStyle CssClass="gridViewSelectedRow" />
<PagerStyle CssClass="gridViewPager" />
</asp:GridView>
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.CssClass = "cssClass";
}
}
You can try something like...
protected void Page_Load(object sender, EventArgs e)
{
GridViewHelper helper = new GridViewHelper(this.GridView1);
helper.RegisterGroup("yourGroupName", true, true);
helper.GroupHeader += new GroupEvent(helper_GroupHeader);
}
private void helper_GroupHeader(string groupName, object[] values, GridViewRow row)
{
if (groupName == "yourGroupName" )
{
row.Cells[0].Text = "<br />" + row.Cells[0].Text;
}
}
You should also be able to insert a new one before row instead of just adding a break line to the cell if that's what you want.
I wrote a method that deletes rows from my an asp.net Gridview when the delete button is clicked and another method for when the edit button is clicked.
Both Edit and Delete buttons are part of the built in gridview controls.
However when I press these buttons (edit/delete)and exception is thrown.
Unable to cast object of type 'System.Web.UI.WebControls.GridView' to type 'System.Web.UI.WebControls.Button'. which is pointing at the line
Button btn = (Button)sender;
The problem here is that this line is not related to either of the edit or delete methods. It is related to the asp button in another column, and for that reason I am lost. How can I resolve this issue? What is causing both the OnRowDeleting and OnRowEditing conflict with the showResponses method?
Here is the aspx
<asp:GridView runat="server" ID="gvShowQuestionnaires" HeaderStyle-CssClass="table_header" CssClass="view" AlternatingRowStyle-CssClass="alt" AlternatingRowStyle-BackColor="#f3f4f8" AutoGenerateColumns="False"
DataKeyNames='QuestionnaireID' OnRowDeleting="gvShowQuestionnaires_RowDeleting" OnRowEditing="gvShowQuestionnaires_RowEdit" FooterStyle-CssClass="view_table_footer" OnRowCommand="showResponses">
<Columns>
<asp:BoundField DataField="QuestionnaireID" HeaderText="ID" HeaderStyle-Width="80px" ItemStyle-CssClass="bo"></asp:BoundField>
<asp:BoundField DataField="QuestionnaireName" HeaderText="Questionnaire Name" />
<asp:TemplateField HeaderText="Results" HeaderStyle-Width="150px">
<ItemTemplate>
<asp:Button runat="server" ID="button1" CommandArgument='<%# Eval("QuestionnaireID") %>' OnClick="showResponses" text="Results"/>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Options" ShowDeleteButton="True" ShowEditButton="true" EditText="Edit"></asp:CommandField>
</Columns>
</asp:GridView>
And here is the code behind:
protected void gvShowQuestionnaires_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int questionnaireID = (int)gvShowQuestionnaires.DataKeys[Convert.ToInt32(e.RowIndex)].Value;
GetData.DeleteQuestionnaire(questionnaireID);
gvShowQuestionnaires.DataSource = DT;
gvShowQuestionnaires.DataBind();
}
protected void gvShowQuestionnaires_RowEdit(object sender, GridViewEditEventArgs e)
{
string id = gvShowQuestionnaires.Rows[e.NewEditIndex].Cells[0].Text;
Session["qID"] = id;
Response.Redirect("~/members/edit_questionnaire.aspx");
}
protected void showResponses(object sender, EventArgs e)
{
Button btn = (Button)sender;
string id = btn.CommandArgument.ToString();
Session["qID"] = id;
Response.Redirect("~/members/questionnaire_responses.aspx");
}
Any help would much appreciated.
It seems reasonably clear to me. Here:
<asp:GridView runat="server" ... OnRowCommand="showResponses">
you bind the RowCommand event to showResponses. And here, in showResponses, you assume that the sender is a button:
protected void showResponses(object sender, EventArgs e)
{
Button btn = (Button)sender;
string id = btn.CommandArgument.ToString();
Session["qID"] = id;
Response.Redirect("~/members/questionnaire_responses.aspx");
}
The sender isn't a button - it's the grid view. If you want the command argument, you should use GridViewCommandEventArgs.CommandArgument.
protected void showResponses(object sender, GridViewCommandEventArgs e)
{
Session["qID"] = e.CommandArgument;
Response.Redirect("~/members/questionnaire_responses.aspx");
}
Add a CommandName attribute to your button1 in the GridView.
<asp:Button runat="server" ID="button1" CommandName="Button1" CommandArgument='<%# Eval("QuestionnaireID") %>' OnClick="showResponses" text="Results"/>
Then in showResponses do this...
protected void showResponses(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Button1") {
Session["qID"] = e.CommandArgument;
Response.Redirect("~/members/questionnaire_responses.aspx");
}
}
var btnSender = (Button)e.CommandSource;
Please consider the values in comments which I got in debug mode:
protected void FilesGrid_SelectedIndexChanged(object sender, EventArgs e)
{
int selected = FilesGrid.SelectedIndex; // selected = 2
FilesGrid.DataBind(); //added after feedback in comments. it makes no change
int count = FilesGrid.Rows.Count; // count = 0
GridViewRow row = FilesGrid.Rows[selected]; // row = null
GridViewRow row0 = FilesGrid.Rows[0]; // row = null
}
I came to this code while investigating why SelectedValue gives null in this event handler (the DataKeyNames parameter was set for sure).
Can anybody explain how it is possible?
Thank you in advance.
PS.
Here is my aspx code:
<asp:GridView ID="FilesGrid" runat="server" AutoGenerateColumns="False"
AutoGenerateSelectButton="True"
onselectedindexchanged="FilesGrid_SelectedIndexChanged"
style="margin-top: 0px" >
<Columns>
<asp:CommandField ShowDeleteButton="True" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Length" DataFormatString="{0:N0}"
HeaderText="Size in Bytes" HtmlEncode="False" />
</Columns>
</asp:GridView>
Here is how I bind data:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string [] dd = {"FullName"};
FilesGrid.DataKeyNames = dd;
string appPath = Request.PhysicalApplicationPath;
DirectoryInfo dirInfo = new DirectoryInfo(appPath);
FileInfo[] files = dirInfo.GetFiles();
FilesGrid.DataSource = files;
FilesGrid.DataBind(); }
}
Y copy pasted your code, delete this line FilesGrid.DataBind() in the FilesGrid_SelectedIndexChanged, i see that are 2 methods that you are not posting, that aren't in the code that you posted the onselectedindexchanging, onrowdeleting events, comment them from the aspx and see if it works, or se if that events are not doing something tricking, that are deleting the rows in your GridView.
Tell me if it works
I did this
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string[] dd = { "FullName" };
FilesGrid.DataKeyNames = dd;
string appPath = Request.PhysicalApplicationPath;
DirectoryInfo dirInfo = new DirectoryInfo(appPath);
FileInfo[] files = dirInfo.GetFiles();
FilesGrid.DataSource = files;
FilesGrid.DataBind();
}
}
protected void FilesGrid_SelectedIndexChanged(object sender, EventArgs e)
{
int selected = FilesGrid.SelectedIndex; // selected = 2
//FilesGrid.DataBind(); //added after feedback in comments. it makes no change
int count = FilesGrid.Rows.Count; // count = 0
GridViewRow row = FilesGrid.Rows[selected]; // row = null
GridViewRow row0 = FilesGrid.Rows[0]; // row = null
}
protected void FilesGrid_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
}
protected void FilesGrid_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
}
The aspx code.
<asp:ScriptManager ID="ScriptManager1" runat="server" EnableScriptGlobalization="true"
AsyncPostBackTimeout="0" EnableScriptLocalization="true">
</asp:ScriptManager>
<asp:UpdatePanel ID="upPanel" runat="server">
<ContentTemplate>
<asp:GridView ID="FilesGrid" runat="server" AutoGenerateColumns="False" AutoGenerateSelectButton="True"
OnRowDeleting="FilesGrid_RowDeleting" OnSelectedIndexChanged="FilesGrid_SelectedIndexChanged"
Style="margin-top: 0px" OnSelectedIndexChanging="FilesGrid_SelectedIndexChanging">
<Columns>
<asp:CommandField ShowDeleteButton="True" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Length" DataFormatString="{0:N0}" HeaderText="Size in Bytes"
HtmlEncode="False" />
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
remove the FilesGrid.DataBind(); //added after feedback in comments. it makes no change
When I add that statement to my code I am getting the error. after removing that please try again. If not working please share the
protected void FilesGrid_SelectedIndexChanging(object sender, GridViewSelectEventArgs e) method code, may be something wrong with that section
The issue was resolved by commenting out the line // if (!Page.IsPostBack). It looks like the data source is lost somehow during the postback. The whole seems to be a local bug with ViewState, because this behavior was not observed by other users. My special thanks to Tim Schmelter and naveen.
You can keep Page.IsPostBack in Page_Load, I was having the same issue and it turns out the grid was not in ViewState in my case. If you use Linq query in your controller you will want to add this property to the grid so it will keep refreshing properly:
<asp:Panel EnableViewState="True">