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">
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 am trying to find the last row of my grid, and programmatically add a drop down list to the grid. My code compiles with no issues, but my RowDataBound is never hit when stepping through the code causing the list to never be added. What have I improperly coded?
EDIT
The page loads and you select an option from the drop down list. RefreshdatagridTest is called at that point.
End Of Edit
ASP Code
<div class="CenterGrid">
<asp:DataGrid runat="server" ID="datagridTest" AutoGenerateColumns="false"
Width="500px" CssClass="DataGrids" HorizontalAlign="Center" GridLines="Both"
ShowFooter="true" OnSelectedIndexChanged="datagridTest_SelectedIndexChanged"
OnItemCommand="datagridTest_ItemCommand" RowDataBound="datagridTest_RowDataBound" Visible="true">
<ItemStyle CssClass="row" />
<FooterStyle CssClass="DataGridFooters" />
<HeaderStyle CssClass="DataGridHeaders" />
<Columns>
<asp:BoundColumn DataField="Firefly" HeaderText="Name"></asp:BoundColumn>
<asp:ButtonColumn CommandName="Delete" HeaderText="Delete From List" Text="[Remove]"></asp:ButtonColumn>
</Columns>
</asp:DataGrid>
</div>
C# Code
protected void datagridTest_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex == datagridTest.Items.Count - 1)
{
DropDownList ddl = new DropDownList();
e.Row.Cells[0].Controls.Add(ddl);
}
}
protected void datagridTest_ItemCommand(object source, DataGridCommandEventArgs e)
{
LinkButton lnkbtn = ((LinkButton)e.CommandSource);
if (e.CommandName == "Delete")
{
DataGridItem deletecontrol = (DataGridItem)lnkbtn.NamingContainer;
string bomb = deletecontrol.Cells[0].Text;
RemoveFireflyFromList(bomb);
RefreshdatagridTest();
}
}
How the grid gets data bound
protected void listselect_SelectedIndexChanged(object sender, EventArgs e)
{
RefreshdatagridTest();
}
private void RefreshdatagridTest()
{
dataSet = Run sql procedure to get results;
this.datagridTest.DataSource = dataSet;
this.datagridTest.DataBind();
}
its bit differente since in my exemple i generate new row at runtime but basicaly its how it work;
in my case had to add some size param or control was hidden.
so i just get to set control row's and add the row to the grid.
Mycontrol m = new Mycontrol();
RowDefinition rowDef1 = new RowDefinition();
rowDef1.MaxHeight = m.ExpandedSise;
rowDef1.MinHeight = m.Height;
rowDef1.Height = new GridLength(m.RowDefColapsedSize);
int rownumber = grid2.RowDefinitions.Count;
grid2.RowDefinitions.Insert(rownumber, rowDef1);
Grid.SetRow(m, rownumber);
m.counter.Content = Grid.GetRow(m).ToString();
grid2.Children.Add(m);
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;
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();
}