Get clicked cell in gridview asp.net - asp.net

I got gridview that I fill with data from my database. I would like to catch an event of click and to get attributes of the cell row and column.
all I found is row click that I can get the row clicked.
also, if there is other component to deploy the data and can get me the cell click event is good enough for me.
HTML:
<div class="grid">
<asp:GridView ID="HistoricGrid" runat="server"></asp:GridView>
</div>
C#
DBconnection db = new DBconnection();
string strtable = "select * from StudentVisit";
DataTable dt = db.ReadDataTable(strtable);
HistoricGrid.DataSource = dt; HistoricGrid.DataBind();
thanks for the help,
Moshe

You should try this.
<asp:GridView ID="GridView1" AutoGenerateColumns="False" ShowHeader="True" runat="server" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField HeaderText="Value" DataField="ItemValue" ReadOnly="true" />
<asp:BoundField HeaderText="Text" DataField="ItemText" ReadOnly="true" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
aspx.cs file
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if ( e.Row.RowType == DataControlRowType.DataRow )
{
LinkButton linkButton = (LinkButton)e.Row.FindControl("LinkButton1");
if (linkButton != null)
{
linkButton.Attributes.Add("onclick", "window.open('someURL'); return false;");
}
}
}

You can use below code
private void gv_Cell_Click(object sender, GridViewCellEventArgs e)
{
int cellindex=e.CellIndex;
int rowindex =e.rowindex;
var value = gv.Rows[rowindex].Cells[cellindex].value;
}

Related

Gridview multiple checkbox selection

I want to check multiple item checkboxes without clicking on the checkbox, rather than on other clicking columns.
Here is my **.cs code
private void gridView2_RowClick(object sender,DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
{
if (gridView2.GetSelectedRows().Count() > 0)
{
foreach (int i in gridView2.GetSelectedRows())
{
gridView2.SelectRow(i);
}
}
}
And, this is my **.designer.cs code
this.gridView2.OptionsSelection.MultiSelect = true;
this.gridView2.OptionsSelection.MultiSelectMode = DevExpress.XtraGrid.Views.Grid.GridMultiSelectMode.CheckBoxRowSelect;
this.gridView2.OptionsSelection.ShowCheckBoxSelectorInGroupRow = DevExpress.Utils.DefaultBoolean.True;
Ok, assuming a gridview?
We have this markup:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" CssClass="table table-hover" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:TemplateField HeaderText="Check Test" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" OnClick="MyCheckBoxClick(this);"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<script>
function MyRowCheck(ctrl) {
MyCheckBox = document.getElementById(ctrl);
MyCheckBox.checked = !MyCheckBox.checked
}
function MyCheckBoxClick(ct) {
ct.checked = !ct.checked
}
</script>
code to load:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadGrid();
}
}
void LoadGrid()
{
using (SqlCommand cmdSQL = new SqlCommand("SELECT TOP 12 * from tblHotels ORDER BY HotelName",
new SqlConnection(Properties.Settings.Default.TEST3)))
{
cmdSQL.Connection.Open();
GridView1.DataSource = cmdSQL.ExecuteReader();
GridView1.DataBind();
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
CheckBox MyCheckBox = (CheckBox)e.Row.FindControl("CheckBox1");
e.Row.Attributes["onclick"] = "MyRowCheck('" + MyCheckBox.ClientID + "');";
}
}
So, we just attach a ROW click to the grid.
We get this output:
this works fine and a click on the row will toggle the check box.
but, the PROBLEM is then if you actually click on the check box. The Row click fires toggles the check box, and then the check box click ALSO fires and un-does what you just did!!
So, I added the on-click event to the check box - and we just toggle the setting again, and we are good to go.

Remove TemplateField during page load or before databind

I want to remove templatefield from gridview during pageload or before databind to GridView. I have 2 data sources for retrieving data. The data retrieved from one of the data sources do not have the columns ExpireDate and ExpireDays.
So I want to delete the templatefields corresponding to ExpireDate and ExpireDays if the GridView is populated from the data source that do not have those 2 fields.
Setting the visibility to false still will have error of DataRowView doesn't contain property name ExpireDate and ExpireDays.
Markup
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="ID" HeaderText="No."/>
<asp:BoundField DataField="Name" HeaderText="Name"/>
<asp:BoundField DataField="CourseName" HeaderText="Course Enroll" />
<asp:BoundField DataField="SubMember" HeaderText="ChildMember" />
<asp:TemplateField HeaderText="Expiry Days">
<ItemStyle HorizontalAlign="Center" />
<ItemTemplate>
<asp:Label runat="server" ID="expDsL" Text=' <%# Eval("ExpiryDays") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Expiry On">
<ItemStyle HorizontalAlign="Center" />
<ItemTemplate>
<asp:Label runat="server" ID="expDeL" Text=' <%# Eval("ExpiryDate") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Function">
<ItemStyle HorizontalAlign="Center" Width="100px"></ItemStyle>
<ItemTemplate>
<asp:ImageButton ImageUrl="~/Images/editB.gif" ID="btnEdit" runat="server" ToolTip="Edit" CommandName="Edit" CommandArgument='<%# Eval("ID") %>' />
<asp:ImageButton ImageUrl="~/Images/delB.gif" ID="btnDelete" runat="server" ToolTip="Delete" CommandName="Delete" CommandArgument='<%# Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
if(Class.ToLower() != "classAA")
{
// using naveen answer can remove the column.
var expiryDateF = ((DataControlField)GridView1.Columns.Cast<DataControlField>().Where(fid => fid.HeaderText == "Expiry Days").SingleOrDefault());
var expiryDaysF = ((DataControlField)GridView1.Columns.Cast<DataControlField>().Where(fid => fid.HeaderText == "Expiry On").SingleOrDefault());
if (expiryDateF != null)
{
GridView1.Columns.Remove(expiryDateF);
}
if (expiryDaysF != null)
{
GridView1.Columns.Remove(expiryDaysF);
}
}
if(!this.IsPostBack)
{
BindData();
}
}
protected void SaveMember(object sender, EventArgs e)
{
//getting member information and perform checking.
bool success = dbbb.AddMem(memberdetails);
if(success == true)
{
BindData();
}
else
{
//prompt fail message.
}
}
protected void BindData()
{
DataTable dt = dbbb.RetrieveList();
if(dt != null)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
ImageButton btnDel = (ImageButton)e.Row.FindControl("btnDelete");
btnDel.Attributes.Add("onclick", "return confirm('Are you sure you want to delete this member?')");
}
}
How could I delete the column?
Two methods to achieve this
Method 1 - Remove by Index
if(!table.Columns.Contains("CustomerID1"))
{
//seven is the column index here. ie, 8th column
CustomersGrid.Columns.RemoveAt(7);
}
Method 2 - Remove using Columns Header Text
var expiryDateField= ((DataControlField)CustomersGrid.Columns
.Cast<DataControlField>()
.Where(fld => fld.HeaderText == "Expiry Date")
.SingleOrDefault());
if(expiryDateField != null)
{
CustomersGrid.Columns.Remove(expiryDateField);
}
Please not that
CustomersGrid is the name of the asp:GridView here.
table is the DataTable that acts as the DataSource of the GridView
The code should be called before DataBind of the GridView
Attach to the rowDataBound event of the grid, there you can set it dynamically.
You have to know the datasource name of the field you want to hide,
for example the headertext for the cell is "SomeHeader", but the databoundfield name for that cell is
"SomeOtherName"
then you have to check it like this (debug through GetColumnIndexByName) and
check the value of
((BoundField)cell.ContainingField).DataField
int GetColumnIndexByName(GridViewRow row, string columnName)
{
int columnIndex = 0;
foreach (DataControlFieldCell cell in row.Cells)
{
if (cell.ContainingField is BoundField)
if (((BoundField)cell.ContainingField).DataField.Equals(columnName))
break;
columnIndex++; // keep adding 1 while we don't have the correct name
}
return columnIndex;
}
remember that the code above will use a BoundField... then use it like:
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int index = GetColumnIndexByName(e.Row, "SomeOtherName");
string columnValue = e.Row.Cells[index].Text;
}
}

itemTemplate item id not existing in code behind

I am trying to create textboxes that are equal to the number of rows in grid view (databound from db). here is my markup
<asp:GridView ID="quizGrid" runat="server" CssClass="Grid" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="admissionNO" HeaderText="Admission NO"/>
<asp:BoundField DataField="studentName" HeaderText="Name" />
<asp:TemplateField>
<ItemTemplate>
<asp:Textbox runat="server" ID="marks" > </asp:Textbox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
but when i use the marks in code behind it says
quizGrid_marks_0 does not exists in the current context
what im doing wrong here?
You can't access your textbox like that in code behind file, rather you need to find them in RowDataBound event like this:-
protected void quizGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
TextBox marks = (TextBox)e.Row.FindControl("marks");
txtMarks.Text = "Test";
}
}
Edit:
Okay, suppose you have a button btnGetData with button click event as btnGetData_Click, then you can find the textbox text by looping through the gridview rows like this:-
protected void btnGetData_Click(object sender, EventArgs e)
{
GridView quizGrid = (GridView)Page.FindControl("quizGrid");
foreach (GridViewRow row in quizGrid.Rows)
{
TextBox marks = (TextBox)row.FindControl("marks");
}
}

Getting row from hyperlink in Gridview

I have a Hyperlink field in a asp.net gridview that runs code behind in an aspx file, like
<asp:GridView ID="gvCoursesList" runat="server">
<Columns>
<asp:BoundField DataField="Course" HeaderText="Course">
</asp:BoundField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lblSignup" runat="server" Text="Sign Up" OnClick= "lblSignup_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
In my code behind file I have the function:
protected void lblSignup_Click(object sender, EventArgs e)
{
}
How do I retrieve the value of the first column from this function.
I would like to do something like
string course = gvCoursesList.DataKeys[e.RowIndex].Value.ToString();
but it's not working. Any other ideas?
#jishnusaha should be the approach you should take. Here is another alternative: http://forums.asp.net/p/1137287/1821091.aspx
protected void lblSignup_Click(object sender, EventArgs e)
{
LinkButton btn = sender as LinkButton;
GridViewRow row = btn.NamingContainer as GridViewRow;
string course = gvCoursesList.DataKeys[row.RowIndex].Value.ToString();
}
<asp:GridView ID="gvCoursesList" runat="server" OnRowCommand="gvCoursesList_RowCommand">
<Columns>
<asp:BoundField DataField="Course" HeaderText="Course">
</asp:BoundField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lblSignup" runat="server" Text="Sign Up" CommandName="SignUp" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
protected void gvCoursesList_RowCommand(object sender, GridViewRowCommandEventArgs e)
{
if(e.CommandName=="SignUp")
{
string course = gvCoursesList.DataKeys[e.RowIndex].Value.ToString();
}
}
Use the .cells.text to get the value out:
protected void lblSignup_Click(object sender, EventArgs e)
{
GridViewRow row = gvCoursesList.rows[e.rowindex]
string course = row.cells[cellIndex].text;
}
With thanks to codingbiz. His solution just needed a little tweak as per below.
LinkButton btn = sender as LinkButton;
GridViewRow row = btn.NamingContainer as GridViewRow;
string course = row.Cells[0].Text;

GridView Delete Not Re-Binding

I have a GridView with a delete template field:
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<asp:GridView ID="gvCurrentDay" CssClass="gridview" OnRowCommand="gvCurrentDay_RowCommand" AutoGenerateColumns="false" runat="server">
<Columns>
<asp:BoundField DataField="ClientName" HeaderText="Client" />
<asp:BoundField DataField="ProjectTitle" HeaderText="Project" />
<asp:BoundField DataField="TimeToAdd" HeaderText="Time Allocated" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center" />
<asp:TemplateField ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:ImageButton ID="imbDeleteRow" ImageUrl="~/images/icons/DeleteRed.png" CommandArgument='<%# Eval("RecordID") %>' CommandName="Delete" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
The code runs when the button is pressed and the database entry is removed from the database, but the GridView is not rebinding, here is the code that controls the delete:
protected void gvCurrentDay_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
int RecordID = Convert.ToInt32(e.CommandArgument);
tdl objTdl = new tdl();
objTdl.DeleteEntryForDay(RecordID);
GetItineryForDay(Convert.ToDateTime(txtCalendar.Text));
lblMessages.Text = "Entry removed";
}
}
And here is the first part of the GetItineryForDay procedure:
protected void GetItineryForDay(DateTime SelectedDate)
{
gvCurrentDay.DataSource = null;
gvCurrentDay.DataBind();
tdl objTdl = new tdl();
DataTable dt = objTdl.GetUsersProjectTimeForDay(SelectedDate, Convert.ToInt32(Request.Cookies["staffid"].Value));
if (dt.Rows.Count > 0)
{
DataRow row = dt.Rows[0];
int TotalTime2 = Convert.ToInt32(row[7]);
string TotalTime = row[7].ToString() + " minutes";
gvCurrentDay.DataSource = dt;
gvCurrentDay.DataBind();
Can you see from the code any reason why the GridView is not updating? The GridView sits in an UpdatePanel.
Instead of using "Delete" as the CommandName, use something else, like "ManualDelete". "Delete" is usually trapped by RowDeleting and RowDeleted events.
Alternatively, and since "the database entry is removed from the database", you could put your rebind code in the RowDeleted event.
protected void gvCurrentDay_RowDeleted(object sender, GridViewDeletedEventArgs e)
{
GetItineryForDay(Convert.ToDateTime(txtCalendar.Text));
lblMessages.Text = "Entry removed";
}

Resources