I have a web app(ASP.NET 2.0 using C#) that I am working on. In it, I have a gridview with a hyperlinkfield on a page(My_Page.aspx). When the Hyperlinkfield is clicked, it shows details on the same page.
<asp:HyperLinkField DataNavigateUrlFields="ID"
DataNavigateUrlFormatString="My_Page.aspx?id={0}"
DataTextField="NAME"
HeaderText="Item1"
SortExpression="NAME" />
I want to know how to find the Index of the row in which the Hyperlink is clicked, because I want to change its style, so that the user knows which row was clicked.
OR
How would I change the style of it when the user clicks hyperlink in the gridview.
Thank you.
In your example, the "index" or rather "id" of the hyperlink that was clicked will be in Request.QueryString["id"]
You could compare the ID from the querystring with the ID of the row you are binding to in the RowDataBound event.
Alternatively you could use a <%# DataBinder.Eval %> in your aspx to set the style based upon the ID field and the query string.
EDIT: Code Sample, try adding this to your code behind.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if(Request.QueryString["id"] != null &&
Request.QueryString["id"] == DataBinder.Eval(e.Row.DataItem, "id").ToString())
{
e.Row.Style.Add("font-weight", "bold");
}
}
}
It is an sample which when you select a row on Gridview child of selected node are shown in the same gridview:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LocationIDHiddenField.Value = Request.QueryString["LocationID"];
}
if (LocationIDHiddenField.Value != null && LocationIDHiddenField.Value != string.Empty)
LoadLocationParents();
}
private void LoadLocationParents()
{
long locationID = Convert.ToInt64(LocationIDHiddenField.Value);
bool IsCurrent = true;
HyperLink parent;
Label seperator;
do
{
Basic.Location.LocationProperties location = Basic.Location.LocationLoader.GetLocationProperties(locationID);
parent = new HyperLink();
seperator = new Label();
if (!IsCurrent)
parent.NavigateUrl = string.Format("LOCATIONLOV.aspx?LocationID={0}", location.LocationID);
IsCurrent = false;
parent.Text = location.LocationTitle;
seperator.Text = " > ";
ParentsPanel.Controls.AddAt(0, parent);
ParentsPanel.Controls.AddAt(0, seperator);
locationID = location.ParentID;
}
while (locationID != 0);
parent = new HyperLink();
parent.NavigateUrl = "LOCATIONLOV.aspx";
parent.Text = "upper nodes";
ParentsPanel.Controls.AddAt(0, parent);
}
GridView
<asp:GridView ID="ChildsGridView" runat="server" AutoGenerateColumns="False" DataKeyNames="LocationID"
DataSourceID="ChildsObjectDataSource" Width="570px" AllowPaging="True">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
</HeaderTemplate>
<ItemStyle Width="20px" />
<ItemTemplate>
<a onclick="if ('<%# Eval("ChildCount") %>' == 'False') return false;" href='<%# Eval("LocationID", "LOCATIONLOV.aspx?LocationID={0}") %>' ><asp:Image ID="GridLocationLov" runat="server" ToolTip="Expand" SkinID="LOVChilds" /></a>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Title" SortExpression="LocationTitleType">
<ItemTemplate>
<span class="LOVSelectText" onclick="LOCATIONID = '<%# Eval("LocationID") %>'; LOCATIONTITLE = <%= ConfirmTextBox.ClientID %>.value = '<%# Eval("LocationTitle") %>';ChangeSelectedRow(this);">
<%# Eval("LocationTitleType")%>
</span>
</ItemTemplate>
<HeaderTemplate>
<asp:Label ID="GridHeadLabel" runat="server" OnLoad="GridHeadLabel_Load"></asp:Label>
</HeaderTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
NO CHild
</EmptyDataTemplate>
</asp:GridView>
DataSource
<asp:ObjectDataSource ID="ChildsObjectDataSource" runat="server" OldValuesParameterFormatString="original_{0}"
SelectMethod="Retrive" TypeName="BASIC.LOCATIONLOV.LOCATIONLOVLoader">
<SelectParameters>
<asp:ControlParameter ControlID="LocationIDHiddenField" Name="ParentID" PropertyName="Value"
Type="Int64" />
<asp:Parameter DefaultValue="LocationTitle" Name="SortExpression" Type="String" />
</SelectParameters>
</asp:ObjectDataSource>
<asp:HiddenField ID="LocationIDHiddenField" runat="server" />
JavaScript
function ChangeSelectedRow(sender)
{
if (SelectedRow != null)
SelectedRow.style.backgroundColor = OriginalColor;
SelectedRow = sender.parentElement.parentElement;
OriginalColor = SelectedRow.style.backgroundColor;
SelectedRow.style.backgroundColor = 'red';
}
Related
I am using entity framework and taking my datas from database and fill my gridview with them.Datas selected by user from a treview.Simply, user selects a data from treeview and I put it to gridview. Lastly I have a button for clearing the gridview. Here is my aspx:
<div id="divPrint" style="background-color: white" runat="server">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<p style="text-align:center">HDCVI KAMERA FİYAT TEKLİFİDİR</p>
<asp:GridView ID="GridViewHdcvi" runat="server" DataSourceID="EntityDataSourceHdcvi" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="ÜRÜN VE DETAYLARI">
<ItemStyle Width="400px" />
<ItemTemplate>
<div style="color: red" class="text-center"><%#Eval("UrunAdi") %></div>
<%#Eval("UrunDetay") %>
</ItemTemplate>
</asp:TemplateField>
<asp:ImageField HeaderText="ÜRÜN GÖRSELİ" DataImageUrlField="UrunResim"></asp:ImageField>
<asp:TemplateField HeaderText="BİRİM FİYAT">
<ItemTemplate>
<%#Eval("UrunFiyati") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ADET">
<ItemTemplate>
<asp:TextBox ID="txtAdet" runat="server" Width="40px"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</div>
<asp:Button ID="btnListiSifirla" runat="server" Text="Listeyi Sıfırla" CssClass="btn btn-danger" OnClick="btnListiSifirla_Click" />
And my codebehind:
static List<string> urunList = new List<string>();
protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
{
string id = TreeView1.SelectedValue;
urunList.Add(id);
listeyiDoldur();
}
protected void listeyiDoldur()
{
if (urunList.Count == 0)
{
failDiv.Visible = true;
}
else
{
string query = "SELECT UrunTable.UrunAdi, UrunTable.UrunFiyati, UrunTable.UrunResim, UrunTable.UrunKategori, UrunTable.UrunDetay FROM UrunTable WHERE ";
foreach (var val in urunList)
{
if (val.Equals(urunList[urunList.Count - 1]))
{
query += "UrunTable.UrunId = " + val;
}
else
{
query += "UrunTable.UrunId = " + val + " || ";
}
}
EntityDataSourceHdcvi.CommandText = query;
divPrint.Visible = true;
btnListiSifirla.Visible = true;
}
}
protected void btnListiSifirla_Click(object sender, EventArgs e)
{
urunList.Clear();
btnListiSifirla.Visible = false;
Page_Load(null,EventArgs.Empty);
}
I can successfully display selected datas in gridview and clear them when button is pressed. Here is the problem: After clearing the gridview I can't add the last added item again.For example if I add item1,item2 and item3 in this order,after clearing the gridview I can't add item3. I can add item1 or item2, then item3. I can't add item firstly which I added last before clearing. I tried clearing gridview in button's onClick and tried other lots of things but nothing gave any result. Thanks for your time.
Greetings to all
Actually i'm developing a web application Which will generate DataGrid,Button and a Label at run time depends upon the value return from database.
Eg:
if return value is 2 then the 3 controls(datagrid,button and label) will generate twice.like shown below
Application working Procedure is.On click on search button the above 3 controls are generated and bind the datagrid.I have achieved this using repeater.
Now what i need is....inside that datagrid i have a button called refresh.When the Refresh button is clicked the gross weight and volume in the datagrid should display the string value,remaining columns should not get change.
Here is my aspx code:
<asp:Repeater runat="server" OnItemDataBound="repeaterSearchResult_ItemDataBound" ID="repeaterSearchResult">
<ItemTemplate>
<asp:Label ID="textBoxSearch" ForeColor="White" width="25%" runat="server"
Text="<%#Container.DataItem%>"></asp:Label>
<asp:Button ID="BTNAdd" runat="server" Text="Add" OnClick="button_click"/>
<br />
<asp:DataGrid ID="dgLCL" runat="server" AutoGenerateColumns="False"
ShowFooter="FALSE" CellPadding="3" OnItemCommand="dgLCL_Select"
OnDeleteCommand="dgLCL_Delete">
<asp:BoundColumn DataField="GrossUOMType" HeaderText="Type">
</asp:BoundColumn>
<asp:BoundColumn DataField="Volume" HeaderText="Volume">
</asp:BoundColumn>
<asp:TemplateColumn HeaderText="DELETE">
<ItemTemplate>
<asp:ImageButton runat="server" ID="IMGBTNDelete"
ImageUrl="~/AppImages/grid-icon-delete.jpg"
ToolTip="Delete" CommandName="DeleteItem"
OnClientClick="javascript:return confirmDelete();"
AlternateText="Delete" />
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Add">
<ItemTemplate>
<asp:ImageButton runat="server" ID="IMGBTNAdd"
ImageUrl="~/AppImages/grid-icon-add.jpg"
ToolTip="Insert" CommandName="InsertItem"
AlternateText="Insert" />
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
<PagerStyle HorizontalAlign="Left" ForeColor="#000066" BackColor="White"
Mode="NumericPages">
</PagerStyle>
</asp:DataGrid><br />
and my code behind is:
protected void repeaterSearchResult_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
string Flag = Session["Flag"].ToString();
if (Flag=="B")
{
e.Item.FindControl("textBoxSearch").Visible = false;
e.Item.FindControl("BTNAdd").Visible = false;
}
DataGrid gv = e.Item.FindControl("dgLCL") as DataGrid;
//
Label label = e.Item.FindControl("textBoxSearch") as Label;
Session["Label"] = label.Text;
Session["FlagB"] = Flag;
Session["GV"] = gv;
gridbind(label.Text, Flag, gv);
}
void gridbind(string label,string Flag,DataGrid gv)
{
try
{
if (Session["Loading"] != null)
{
PortLName.Text = Session["Loading"].ToString();
}
if (Session["Destination"] != null)
{
PortDName.Text = Session["Destination"].ToString();
}
string SFRID = label;
if (Flag == "L")
{
sql = "Select MasterNo , MasterDate,GrossWt,GrossUOMType,Volume,tBLg_NUPKId from VW_TransLCLMaster where tBLG_mDOC_NUPKID ='107' and tBLG_NUIsActive=1 and PortOfDischargeName='" + SFRID + "'";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
if (gv != null)
{
gv.DataSource = ds;
gv.DataBind();
}
}
}
catch (Exception ex)
{
}
as shown in above image i need the string values should assign to grosswt and volume on refresh button click.
Please help me thanks in advance.
In your datagrid columns add another column
<asp:TemplateColumn HeaderText="Refresh">
<ItemTemplate>
<asp:ImageButton runat="server" ID="IMGBTNRefresh"
ImageUrl="~/AppImages/grid-icon-refresh.jpg"
ToolTip="Insert" CommandName="Refresh"
AlternateText="Refresh" />
</ItemTemplate>
</asp:TemplateColumn>
In your DagaGrid's OnItemCommand event, set the text for both the cells as below
protected void dgLCL_Select(object source, DataGridCommandEventArgs e)
{
if (e.CommandName == "Refresh")
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
//Change the indexes to correct column index
e.Item.Cells[3].Text = "your dynamic gross weight text";
e.Item.Cells[5].Text = "your dynamic volumne text";
}
}
}
I am about to develop a web application which is used to search and fetch the data from the database as per the criteria which we enter in textboxes.
I have from place and to place once we enter the data in either textbox and hit search button it will fetch data from database and display in textbox (dynamic).
Eg:
if I enter a place kolkata and hit enter then it will count the total no of records that has the from place kolkatta. If count is 3 then 3 textboxes, 3 buttons (add) and 3 gridviews should be created dynamically. Then if we click the add button it will redirect to next page.
I have created a textbox and a button but I'm unable to create 3 gridviews and also click event for the button is not firing.
Here is my code for creating controls dynamically on search button click:
protected void BTNSearch_Click(object sender, EventArgs e)
{
if(Convert.ToInt32( Session["Count"])>0)
{
if (Flag != "")
{
LoadControls(Flag);
}
}
}
private void LoadControls(string Flag)
{
LocationName.Clear();
Session["Flag"] = Flag;
Updatesearch.Update();
dynamicTextBoxes = new TextBox[Convert.ToInt32(Session["Count"])];
dynamicButtons = new Button[Convert.ToInt32(Session["Count"])];
dynamicGV = new GridView[Convert.ToInt32(Session["Count"])];
int i;
if (Flag == "L")
{
sql = "Select PortOfDischargeName from VW_TransAIHBLMasterUpdateDetails where tBLG_NUIsActive=1 and PortOfLoadName='" + Session["Loading"].ToString() + "' group by PortOfDischargeName";
}
else if (Flag == "D")
{
sql = "Select PortOfLoadName from VW_TransAIHBLMasterUpdateDetails where tBLG_NUIsActive=1 and PortOfDischargeName='" + Session["Destination"].ToString() + "' group by PortOfLoadName";
}
else
{
sql = "";
}
SqlDataReader rdr = mobjGenlib.objDBLib.ExecuteQueryReader(sql.ToString());
while (rdr.Read())
{
LocationName.Add(rdr.GetValue(0).ToString());
}
rdr.Close();
for (i = 0; i < Convert.ToInt32(Session["Count"]); i += 1)
{
TextBox textBox = new TextBox();
textBox.ID = "myTextBox" + i.ToString();
textBox.Width = 200;
textBox.Height = 15;
//textBox.Text = String.Empty;
textBox.Text = LocationName[i].ToString();
textBox.BackColor = System.Drawing.Color.AliceBlue;
myPlaceHolder.Controls.Add(textBox);
dynamicTextBoxes[i] = textBox;
var button = new Button();
button.ID = "BtnAdd" + i.ToString();
button.Text = "Add";
//button.Click += button_Click;
button.Click += new System.EventHandler(button_click);
//btn.Click += new EventHandler(btn_Click);
myPlaceHolder.Controls.Add(button);
dynamicButtons[i] = button;
ViewState["Btn"] = dynamicButtons[i];
LiteralControl literalBreak = new LiteralControl("<br />");
myPlaceHolder.Controls.Add(literalBreak);
gv.ID = "gridview" + i;
myPlaceHolder.Controls.Add(gv);
dynamicGV[i] = gv;
BindGrid(textBox.Text, Flag, i);
LiteralControl literalBreak1 = new LiteralControl("<br />");
myPlaceHolder.Controls.Add(literalBreak1);
}
}
This is for button click:
protected void button_click(object sender, EventArgs e)
{
Button btn = (Button)sender;
foreach (Button bt in dynamicButtons)
{
for (int i = 0; i < Convert.ToInt32(Session["Count"]); i++)
{
if (btn.ID == ("BtnAdd" + i))
{
Response.Redirect("FrmTransLCLConsolidation.aspx");
break;
}
}
}
}
**
> i dont know how to write code to the Datagrid onitemcommand and > ondeletecommand.
**
Can anyone help me to achieve this? Thanks in advance.
another issue:
aspx page:
<asp:Repeater runat="server" OnItemDataBound="repeaterSearchResult_ItemDataBound" ID="repeaterSearchResult">
<ItemTemplate>
<asp:Label ID="textBoxSearch" ForeColor="White" width="25%" runat="server" Text="<%#Container.DataItem%>"></asp:Label>
<%--<asp:TextBox ID="textBoxSearch" runat="server" Text="<%#Container.DataItem%>"></asp:TextBox>--%>
<asp:Button ID="BTNAdd" runat="server" Text="Add" OnClick="button_click"/><br />
<asp:DataGrid ID="dgLCL" runat="server" BorderWidth="1px" BorderColor="#FE9B00"
BorderStyle="Solid" BackColor="White" Font-Names="Verdana" Font-Size="XX-Small"
AutoGenerateColumns="False" ShowFooter="FALSE" CellPadding="3" align="center"
Width="700px" OnItemCommand="dgLCL_Select" OnDeleteCommand="dgLCL_Delete">
<FooterStyle ForeColor="#000066" BackColor="White"></FooterStyle>
<SelectedItemStyle Font-Bold="True" ForeColor="Black" BackColor="Snow"></SelectedItemStyle>
<EditItemStyle BackColor="AntiqueWhite"></EditItemStyle>
<PagerStyle BackColor="#FDE9CB" ForeColor="#003399" HorizontalAlign="Right" Mode="NumericPages"
Position="Bottom" Font-Size="Small" Font-Bold="true" />
<AlternatingItemStyle BackColor="Snow"></AlternatingItemStyle>
<ItemStyle ForeColor="#000066" BackColor="Snow"></ItemStyle>
<HeaderStyle Font-Size="XX-Small" Font-Bold="True" Height="10px" ForeColor="#000000"
BackColor="#FFDBA6"></HeaderStyle>
<Columns>
<asp:TemplateColumn>
<ItemTemplate>
<asp:ImageButton runat="server" ID="IMGBTNAdd" ImageUrl="~/AppImages/grid-icon-add.jpg"
ToolTip="Insert" CommandName="SelectItem" AlternateText="Insert" />
</ItemTemplate>
</asp:TemplateColumn>
<asp:BoundColumn DataField="MasterNo" HeaderText="MasterNo"></asp:BoundColumn>
<asp:BoundColumn DataField="MasterDate" HeaderText="MasterDate"></asp:BoundColumn>
<asp:BoundColumn DataField="GrossWt" HeaderText="GrossWt"></asp:BoundColumn>
<asp:BoundColumn DataField="GrossUOMType" HeaderText="Type"></asp:BoundColumn>
<asp:BoundColumn DataField="Volume" HeaderText="Volume"></asp:BoundColumn>
<asp:TemplateColumn HeaderText="DELETE">
<ItemTemplate>
<asp:ImageButton runat="server" ID="IMGBTNDelete" ImageUrl="~/AppImages/grid-icon-delete.jpg"
ToolTip="Delete" CommandName="DeleteItem" OnClientClick="javascript:return confirmDelete();"
AlternateText="Delete" />
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
<PagerStyle HorizontalAlign="Left" ForeColor="#000066" BackColor="White" Mode="NumericPages">
</PagerStyle>
</asp:DataGrid><br />
</ItemTemplate>
</asp:Repeater>
Repeater is a good candidate for this problem. Instead of adding the textboxes dynamically use a repeater control here, which is then easier to maintain.
Below is the outline of what you can do.
<asp:Repeater runat="server" OnItemDataBound="repeaterSearchResult_ItemDataBound" ID="repeaterSearchResult">
<ItemTemplate>
<asp:TextBox ID="textBoxSearch" runat="server" Text="<%#Container.DataItem%>"></asp:TextBox>
<asp:Button ID="buttonAdd" runat="server" Text="Button" OnClick="button_click"/>
<asp:GridView ID="gridView" runat="server">
<%--Add the Columns you want to display--%>
</asp:GridView>
</ItemTemplate>
</asp:Repeater>
In your code, after getting the search result from the data reader, instead of creating the textbox and buttons, bind the result to the repeater
SqlDataReader rdr = mobjGenlib.objDBLib.ExecuteQueryReader(sql.ToString());
while (rdr.Read())
{
LocationName.Add(rdr.GetValue(0).ToString());
}
rdr.Close();
repeaterSearchResult.DataSource = LocationName;
repeaterSearchResult.DataBind();
In the repeaters OnItemDataBound, bind the grid view
protected void repeaterSearchResult_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
GridView gv = e.Item.FindControl("gridView") as GridView;
TextBox textBox = e.Item.FindControl("textBoxSearch") as TextBox;
if (gv != null)
{
//Bind gridview here
}
}
In the button click event you can redirect to the page. You can also use the command argument for the button to identify the current index if you want.
Further to your question to open a new form you can use the following method.
In your image button add onclientclick event as below.
<asp:ImageButton runat="server" OnClientClick="return openNewForm();" ID="IMGBTNAdd" ImageUrl="~/AppImages/grid-icon-add.jpg"
ToolTip="Insert" CommandName="SelectItem" AlternateText="Insert" />
Then add a javascript function to open the popup
<script type="text/javascript">
function openNewForm() {
window.open("url for the new form", "newForm", "menubar=0,resizable=1,location=0,status=0,scrollbars=1,height=500,width=600");
return false;
}
</script>
I have a GridView that has a column that contains emails. I want the user to be able to double click the row and an email link is activated to open an outlook window for an email. I've got the double click part down, but I'm no sure how to get the email from the row to create the url. I'll paste the code I do have below.
<asp:GridView ID="gvAllDOL" runat="server" Visible="False" PageSize="25" AutoGenerateColumns="False" OnDataBound="gvAllDOL_DataBound" DataSourceID="odsDOAll" OnRowDataBound="gvAllDOL_RowDataBound" DataKeyNames="sintDistrictOfficeID" OnRowCommand="gvAllDOL_RowCommand" OnSelectedIndexChanged="gvAllDOL_SelectedIndexChanged">
<Columns>
<asp:ButtonField Text="DoubleClick" CommandName="DoubleClick" Visible="false" />
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblid" runat="server" Text='<%# Bind("sintDistrictOfficeID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="sintDistrictOfficeID" HeaderText="id" SortExpression="sintDistrictOfficeID" />
<asp:BoundField DataField="vcharDOLOfficeName" HeaderText="DOL Office Name" SortExpression="vcharDOLOfficeName" />
<asp:BoundField DataField="vcharDOLCity" HeaderText="City" SortExpression="vcharDOLCity" />
<asp:BoundField DataField="vcharDOLState" HeaderText="State" SortExpression="vcharDOLState" />
<asp:BoundField DataField="intBatchCount" HeaderText="Number Batches" SortExpression="intBatchCount" />
<asp:BoundField DataField="intCaseCount" HeaderText="Number Cases" SortExpression="intCaseCount" />
<asp:BoundField DataField="intExamCount" HeaderText="Number Examiners" SortExpression="intExamCount" />
</Columns>
</asp:GridView>
protected void gvCE_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onMouseOver", "Highlight(this)");
e.Row.Attributes.Add("onMouseOut", "UnHighlight(this)");
// Get the LinkButton control in the second cell
LinkButton _doubleClickButton = (LinkButton)e.Row.Cells[0].Controls[0];
// Get the javascript which is assigned to this LinkButton
string _jsDouble =
ClientScript.GetPostBackClientHyperlink(_doubleClickButton, "");
// Add this JavaScript to the ondblclick Attribute of the row
e.Row.Attributes["ondblclick"] = _jsDouble;
}
}
protected void gvCE_RowCommand(object sender, GridViewCommandEventArgs e)
{
string email = ((Label)gvCE.Rows[0].Cells[1].FindControl("lblEmail")).Text; (this doesn't work)
GridView _gridView = (GridView)sender;
string _commandName = e.CommandName;
switch (_commandName)
{
case ("DoubleClick"):
Response.Redirect("<a href=mailto:" + email + ">");
break;
}
}
protected override void Render(HtmlTextWriter writer)
{
foreach (GridViewRow r in gvAllDOL.Rows)
{
if (r.RowType == DataControlRowType.DataRow)
{
Page.ClientScript.RegisterForEventValidation
(r.UniqueID + "$ctl00");
Page.ClientScript.RegisterForEventValidation
(r.UniqueID + "$ctl01");
}
}
foreach (GridViewRow r in gvCE.Rows)
{
if (r.RowType == DataControlRowType.DataRow)
{
Page.ClientScript.RegisterForEventValidation
(r.UniqueID + "$ctl00");
Page.ClientScript.RegisterForEventValidation
(r.UniqueID + "$ctl01");
}
}
base.Render(writer);
}
Convert your email field into template one. Add the following code and then try playing with it:
<asp:HyperLink ID="EmailLink" runat="server" Text='Email' NavigateUrl=
"mailto:" + '<%# Eval("yourBoundEmailFieldNameHere") %>'
</asp:HyperLink>
I would use Manul's suggestion on adding the email address through an item template
<asp:HyperLink ID="EmailLink" runat="server" Text='Email' NavigateUrl=
"mailto:" + '<%# Eval("yourBoundEmailFieldNameHere") %>'
</asp:HyperLink>
This way you can access the email address and people can see who they will be emailing.
then add this script to the page
$("table tr").dblclick(function () {
var mailto_link = $('a', $(this)).attr('href');
window = window.open(mailto_link, 'emailWindow');
if (window && window.open && !window.closed)
window.close();
});
then remove the code that is adding javascript functions to each row in the grid, because it is no longer needed.
here is a jsfiddle link http://jsfiddle.net/gorrilla/jEX7Y/
You can use command argument to pass the email address, greatly simplifying the logic necessary to retrieve the address.
Change the Command button column to an TemplateField and add a asp:button inside. Then add the attribute CommandArgument to the button.
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="dblClick" runat="server" Text="dblClick"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"
CommandName="dblClick" />
</ItemTemplate>
</asp:TemplateField>
Then in the code behind
protected void gvCE_RowCommand(object sender, GridViewCommandEventArgs e)
{
string email = e.CommandArgument;
My GridView basically displays a summarized version of data in the database.
What I want to do is set it up so that when you click anywhere in a row in the GridView, it should execute a set procedure that'll hide the panel that contains the GridView and display a panel that will show you the details of the item you clicked.
<asp:Panel runat="server" ID="pnlList">
<div class="rightalign">
<asp:Label runat="server" ID="lblCount"></asp:Label>
</div>
<asp:GridView runat="server" ID="gvItems" DataKeyNames="mailid"
AutoGenerateColumns="false" onrowdatabound="gvItems_RowDataBound"
Width="100%" OnSelectedIndexChanged="gvItems_SelectedIndexChanged">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox runat="server" ID="chkSelect" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label runat="server" ID="lblStatus" Text='<%# DataBinder.Eval(Container.DataItem, "status") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="firstname" HeaderText="From" SortExpression="firstname" />
<asp:BoundField DataField="datesent" HeaderText="Date" SortExpression="datesent" DataFormatString="{0:yyyy/MM/dd HH:mm}" />
<asp:BoundField DataField="subject" HeaderText="Subject" SortExpression="subject" />
</Columns>
</asp:GridView>
</asp:Panel>
<asp:Panel runat="server" ID="pnlMail">
<p>From: <asp:Label runat="server" ID="lblFrom"></asp:Label><br />
Sent On: <asp:Label runat="server" ID="lblDate"></asp:Label><br />
Subject: <asp:Label runat="server" ID="lblSubject"></asp:Label></p>
<p><asp:Label runat="server" ID="lblMessage"></asp:Label></p>
</asp:Panel>
I figured I'd use the SelectedIndexChanged event, but I'm not sure how to actually make it fire off clicks on the cells.
Here's the code I've got:
protected void gvItems_SelectedIndexChanged(object sender, EventArgs e)
{
int index = gvItems.SelectedIndex;
string mailid = gvItems.DataKeys[index].Value.ToString();
getMailDetail(mailid);
pnlMail.Visible = true;
}
protected void getMailDetail(string id)
{
int mailid = int.Parse(id);
MySqlContext db = new MySqlContext();
string sql = "select m.datesent, m.subject, m.message, u.firstname, u.lastname from mail m inner join users u on m.senderid = u.userid where m.mailid = #id";
List<MySqlParameter> args = new List<MySqlParameter>();
args.Add(new MySqlParameter() { ParameterName = "#id", MySqlDbType = MySqlDbType.Int32, Value = mailid });
MySqlDataReader dr = db.getReader(sql, args);
if (dr.HasRows)
{
dr.Read();
lblFrom.Text = (string)dr["firstname"] + " " + (string)dr["lastname"];
lblDate.Text = (string)dr["datesent"];
lblSubject.Text = (string)dr["subject"];
lblMessage.Text = (string)dr["message"];
}
dr.Close();
}
How can I make clicks on the cells in a row fire an event that'll do the work I need done?
Any help will be appreciated!
I can see two possible solutions here. First - handle click on the row on client side, send Ajax request to some HttpHandler that will return you necessary mail details, and display the returned info. Steps to achieve this:
Assign a client side handler too row click:
protected void gvItems_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onClick"] = "showMailDetails(" + DataBinder.Eval(e.Row.DataItem, "id") + ")";
}
}
And define the client side function:
function showMailDetails(mailId) {
$.get(
url: 'url to HttpHandler here',
data: {id: mailId},
success: function(data) {
var pnlMail = $('#<%= pnlMail.ClientID %>');
// display data here
pnlMail.show()
});
}
Another way is to handle click on client side and then emulate RowCommand event by doing something like this:
protected void gvItems_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onClick"] = ""javascript:__doPostBack('" + gvItems.ClientID + "','MailDetailsCommand$" + DataBinder.Eval(e.Row.DataItem, "id") + "')";
}
}
And then on server side go like you already did, just in RowComamnd handler:
protected void gvItems_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "MailDetailsCommand") {
// ...
}
}
Although I would not recommend this method - using _doPostBack manully is not considered as a best practice.
you give a template field which consist the button or a button field and then you can the give the commandname as something and then you can use the gridview commandeventargs and based on the commandname you can do whatever you want, and you can use the OnRowCommand to fire an event :D hope this will help you .....
You can even go for adding the onclick attribute to the cell in the RowDataBound Event, if there are any restrictions of not having the button field or like that