I have a GridView like so:
<asp:GridView runat="server" ID="grdPractices" PageSize="10" AutoGenerateColumns="False" DataKeyNames="Id"
CssClass="linkGrid" AllowSorting="True" OnSorting="grdPractices_OnSorting" OnRowDataBound="grdPractices_OnRowDataBound"
OnRowEditing="grdPractices_OnRowEditing" OnRowCancelingEdit="grdPractices_OnRowCancelingEdit" OnRowUpdating="grdPractices_OnRowUpdating">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" meta:resourcekey="PracticeName" ReadOnly="True" SortExpression="Name" ItemStyle-Width="400px" />
<asp:BoundField DataField="Code" HeaderText="Code" meta:resourcekey="Code" ReadOnly="True" SortExpression="Code" ItemStyle-Width="200px" />
<asp:TemplateField meta:resourcekey="SiteName" ItemStyle-Width="200px" SortExpression="SiteName">
<ItemTemplate>
<asp:Literal runat="server" Text='<%# Eval("SiteName") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList runat="server" ID="lstSites" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField meta:resourcekey="NumOfUsers" ItemStyle-Width="200px" SortExpression="NumOfUsers">
<ItemTemplate>
<asp:LinkButton runat="server" OnCommand="OnLinkButtonCommand" CommandName="ViewUsers" Text='<%# Eval("NumOfUsers") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowDeleteButton="False" ShowCancelButton="True"
ShowInsertButton="False" ShowEditButton="True" EditText="Edit"
CancelText="Cancel" UpdateText="Update" meta:resourcekey="Edit" ItemStyle-Width="200px" />
</Columns>
</asp:GridView>
and here is the code for the OnRowEditing event:
protected void grdPractices_OnRowEditing(object sender, GridViewEditEventArgs e)
{
this.grdPractices.EditIndex = e.NewEditIndex;
var sitesDropDown = this.grdPractices.Rows[e.NewEditIndex].Controls[0].FindControl("lstSites") as DropDownList;
if (sitesDropDown == null)
{
return;
}
}
My problem is that I cannot get a hold of the lstSites control, which lives in the EditTemplate. I've tried using the following:
this.grdPractices.Rows[e.NewEditIndex].Controls[0].FindControl("lstSites")
as DropDownList;
this.grdPractices.Rows[e.NewEditIndex].FindControl("lstSites") as
DropDownList;
this.grdPractices.Rows[e.NewEditIndex].FindControlRecursive("lstSites")
as DropDownList;
The result is always the same, a NULL is returned.
How on earth are you supposed to get a control in a row when in the OnRowEditing event?
OK, what I was not doing, after this line:
this.grdPractices.EditIndex = e.NewEditIndex;
was then rebinding the grid's data. So after rebinding the data, and then calling:
var sitesDropDown = this.grdPractices.Rows[e.NewEditIndex].FindControlRecursive("lstSites") as DropDownList;
I am now able to interact with the siteDropDown variable since it now contains a reference to the lstSites control.
Try to use GridViewRow as following...
protected void grd_RowEditing(object sender, GridViewEditEventArgs e)
{
GridViewRow selectRow = grd.Rows(e.NewEditIndex);
DropDownList sitesDropDown =(DropDownList)selectRow.Cells[2].FindControl("lstSites");
}
Related
I have a problem with asp.net gridviewpager. When i click pager any page it routes to OnRowCommand event. I am waiting to route OnPageIndexChanging
I have define my gridview like this.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" DataKeyNames="Id"
GridLines="None" PageSize="4" AllowPaging="True" EmptyDataText="No record found"
OnPageIndexChanging="OnPaging" OnRowDeleting="GridView1_RowDeleting" OnRowCommand="RowCommand"
CssClass="mGrid" PagerStyle-CssClass="pgr" AlternatingRowStyle-CssClass="alt">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" />
<asp:BoundField DataField="Baslik" HeaderText="Baslik" />
<asp:BoundField DataField="KisaAciklama" HeaderText="Kısa Acıklama" />
<asp:TemplateField HeaderText="Güncelle">
<ItemTemplate>
<asp:LinkButton runat="server" ID="lnkView" CommandArgument='<%#Eval("Id") %>' CommandName="VIEW">Güncelle</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sil">
<ItemTemplate>
<asp:LinkButton runat="server" ID="lnkDelete" CommandArgument='<%#Eval("Id") %>'
CommandName="DELETE">Sil</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<%----%>
</Columns>
</asp:GridView>
Also my back-end code is
protected void RowCommand(object sender, GridViewCommandEventArgs e)
{
LinkButton lnkView = (LinkButton)e.CommandSource;
string Id = lnkView.CommandArgument;
if (e.CommandName == "VIEW")
{
Response.Redirect("/Views/AdminPages/Kayit.aspx?cmd=Update&id="+Id);
}
else if (e.CommandName == "DELETE")
{
kayitService.DeleteKayit(Convert.ToInt32(Id));
}
}
protected void OnPaging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
}
Please try this
<asp:GridView ID="Gridview1" runat="server" AutoGenerateColumns="False" BackColor="White"
BorderColor="#3366CC" BorderStyle="None" BorderWidth="1px" CellPadding="4"
onpageindexchanging="gvPerson_PageIndexChanging"
onrowcancelingedit="gvPerson_RowCancelingEdit"
onrowdatabound="gvPerson_RowDataBound" onrowdeleting="gvPerson_RowDeleting"
onrowediting="gvPerson_RowEditing" onrowupdating="gvPerson_RowUpdating"
onsorting="gvPerson_Sorting">
<asp:BoundField DataField="Id" HeaderText="Id" />
<asp:BoundField DataField="Baslik" HeaderText="Baslik" />
<asp:BoundField DataField="KisaAciklama" HeaderText="Kısa Acıklama" />
<asp:TemplateField HeaderText="Güncelle">
<ItemTemplate>
<asp:LinkButton runat="server" ID="lnkView" CommandArgument='<%#Eval("Id") %>' CommandName="VIEW">Güncelle</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sil">
<ItemTemplate>
<asp:LinkButton runat="server" ID="lnkDelete" CommandArgument='<%#Eval("Id") %>'
CommandName="DELETE">Sil</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<%----%>
</Columns>
Back-end code may be :
protected void gvPerson_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
// Set the index of the new display page.
Gridview1.PageIndex = e.NewPageIndex;
// Rebind the GridView control to
// show data in the new page.
BindGridView();
}
According to my opinion the code which I mentioned above is the most appropriate code for Paging.
I have a gridview which have some columns. I have made name column as a hyperlink.
I have a table named- 'tblAdd'. On Page load event I made it invisible. I want that when I click column hyperlink, table display.
How can I do this using asp.net ?
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="Name"
DataSourceID="SqlDataSource1" OnCheckedChanged="sellectAll"
>
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="cbSelectAll" runat="server" AutoPostBack="true" OnCheckedChanged="sellectAll" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chk" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name"
SortExpression="Name" >
<ItemTemplate>
<asp:HyperLink ID="linkName" runat="server" Text='<%#Bind("Name") %>' OnClick="displayTutorial_Click" NavigateUrl='#'>
</asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
My Default.aspx.cs-
protected void Page_Load(object sender, EventArgs e)
{
Label1.Visible = false;
GridView1.Columns[2].Visible = false;
//GridView1.DataBind();
if (!Page.IsPostBack)
{
fillLanguageGrid();
tblAdd.Visible = false;
}
}
Do it using Grid View row command event.
Do something like this-
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
//To get the Selected link text field on textbox
if (e.CommandName == "displayLink")
{
txtEditName.Text=((LinkButton)e.CommandSource).Text;
}
}
On default.aspx-
<asp:TemplateField HeaderText="Name" SortExpression="Name" >
<ItemTemplate>
<asp:LinkButton ID="linkName" runat="server" Text='<%#Bind("Name")%>' OnClick="linkBtn_Click" CommandName="displayLink"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
I am having issue when updating gridview! everything is seems to be working. but when i hit finish editing the data will not save!
but when i click edit the correct fields prompt me to enter new value but it wont save!
here is my asp
<asp:GridView ID="GridView1" runat="server" CssClass="report"
AutoGenerateColumns="False" onrowediting="GridView1_RowEditing"
DataKeyNames="TimeID" onrowupdating="GridView1_RowUpdating"
onrowcommand="GridView1_RowCommand"
onrowcancelingedit="GridView1_RowCancelingEdit">
<Columns>
<asp:BoundField DataField="date" Visible="true" ReadOnly="true" HeaderText="Date" />
<asp:BoundField DataField="Description" HeaderText="Stage Description" ReadOnly="True" />
<asp:TemplateField HeaderText="Start Time">
<ItemTemplate>
<asp:Label ID="Label7" runat="server" Text='<%# ConvertToShotTime(Eval("StartTime")) %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtStartTime" ValidationGroup="1" Width="90px" class="TimeEntry" runat="server" Text='<%# ConvertToShotTime(Eval("StartTime")) %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator6" ControlToValidate="txtStartTime" runat="server" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="End Time">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# ConvertToShotTime(Eval("EndTime")) %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEndTime" class="TimeEntry" ValidationGroup="1" Width="90px" runat="server" Text='<%# ConvertToShotTime(Eval("EndTime")) %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator66" ControlToValidate="txtEndTime" runat="server" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="TimeInHours" HeaderText="Time Time (Hours)" ReadOnly="True" />
<asp:CommandField ShowEditButton="true" ShowCancelButton="true"
ButtonType="Image" EditImageUrl="~/images/edit_record.jpg"
CancelImageUrl="~/images/edit_no.jpg"
UpdateImageUrl="~/images/update_record.jpg" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:ImageButton ID="lnbCopy" runat="server" AlternateText="Delete"
CommandName="DeleteRecord" CommandArgument='<%# Bind("TimeID") %>' OnClientClick="return confirm('Are you sure you want to delete this row?');" ImageUrl="~/images/delete_record.jpg" />
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblTimeID" runat="server" Text='<%# Eval("TimeID") %>'></asp:Label>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
here is what i have done in behind code
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) {
GridView1.EditIndex = e.NewEditIndex;
loadTable();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) {
GridView1.EditIndex = -1;
loadTable();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) {
GridViewRow row = GridView1.Rows[e.RowIndex] as GridViewRow;
var StartTime = row.FindControl("txtStartTime") as TextBox;
var EndTime = row.FindControl("txtEndTime") as TextBox;
var id = row.FindControl("lblTimeID") as Label;
SqlConnection conn = new SqlConnection(conStr.GetConnectionString("myServer1"));
SqlCommand comm = new SqlCommand();
comm.CommandText = "UPDATE CDSTimeSheet SET StartTime = #StartTime, EndTime = #EndTime ,timeElapsed = datediff(minute,#startTime , #EndTime), timeInSeconds = datediff(second,#startTime , #EndTime) WHERE TimeID = #id";
comm.Connection = conn;
comm.Parameters.AddWithValue("#id", id.Text);
comm.Parameters.AddWithValue("#StartTime", StartTime.Text);
comm.Parameters.AddWithValue("#EndTime", EndTime.Text);
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
GridView1.EditIndex = -1;
loadTable();
}
what am i doing wrong?
It sounds a lot like you are not calling DataBind on your grid after updating the underlying data. After you perform the update (possibly within the loadTable method that I see referenced up there), call
GridView1.DataBind();
That should refresh the data in the grid.
After your comments, I see that you're not using the NewValues collection in the GridViewUpdateEventArgs parameter to get the actual incoming, updated field values. Try this:
String StartTime = e.NewValues["StartTime"].ToString();
String EndTime = e.NewValues["EndTime"].ToString();
String id = e.Keys[0].ToString();
Note that these variables are strings now, not TextBoxs, so you don't need to add ".Text" on them when you add them as parameters.
Handle the postback, basically if you fill the grid view in each postback you are re filling the gridview with old data, that's why you retrieve data with no changes (remember after Update button this trigger a postback). So, in case this is your case, try this.
if(!this.IsPostback)
{
(Method that fills your GridView)
}
i have a checkbox in a template field of a gridview and i want to get the id of the record at a checkbox tick. how do i do it? i am doing asp.net and also by using datakeynames instead, my gridview also shows the datakeynames persID column. why?
my code:
<asp:GridView ID="GridViewHostelMember" runat="server" DataKeyNames="_PersID" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="_PersID" HeaderText="_PersID" />
<asp:BoundField DataField="FirstName" HeaderText="First Name" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="DOB" HeaderText="DOB" />
<asp:BoundField DataField="FatherName" HeaderText="FatherName" />
<asp:BoundField DataField="Type" HeaderText="Type" />
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBoxSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow item in this.GridViewHostelMember.Rows)
{
CheckBox chbTemp = item.FindControl("CheckBoxSelect") as CheckBox;
if (chbTemp != null)
{
if (chbTemp.Checked)
{
Label1.Text = item.Cells[0].Text;
}
}
}
}
_PersID is showing because autogeneratecolumns is set to true; if true, it shows all columns. To hide, set to false, and explicitly add the columns to the grid.
For the first part, at checkbox tick, you would need to set AutoPostBack="true" on the checkbox, which posts back, and then you can check the data key for the current row of the grid.
Reference -
my gridview also shows the datakeynames persID column. why?
true to automatically create bound fields for each field in the data
source; otherwise, false. The default is true.
It should be like below..
<asp:GridView ID="GridViewHostelMember" autogeneratecolumns="False"
runat="server" DataKeyNames="_PersID">
i want to get the id of the record at a checkbox tick. how do i do it?
Sample Code
protected void CheckBox_Checked(object sender, EventArgs e)
{
CheckBox c = (CheckBox)sender;
//c.ValidationGroup is your ID
}
Sample HTML
<asp:GridView ID="ed" runat="server" OnRowCommand="GridView_RowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chk" runat="server" AutoPostBack="true" ValidationGroup='<%#Eval("ID") %>' OnCheckedChanged="CheckBox_Checked" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
As my gridview is populating I want to add an extra column with some buttons in but I can't seem to figure out how, or what might be the best way. Can anyone get me started?
Use a Template Column
<asp:GridView ID="GridView1" runat="server" DataKeyNames="id" DataSourceID="SqlDataSource1"
OnRowCommand="GridView1_OnRowCommand">
<Columns>
<asp:BoundField DataField="name" HeaderText="Name" />
<asp:BoundField DataField="email" HeaderText="Email" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:Button ID="Button1" runat="server" CausesValidation="false" CommandName="SendMail"
Text="SendMail" CommandArgument='<%# Eval("id") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void GridView1_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName != "SendMail") return;
int id = Convert.ToInt32(e.CommandArgument);
// do something
}