I have a gridview in an update panel with the following code to select a row, this in turn updates another updatepanel with details from the form record.
protected void gvMainGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Make the entire row clickable to select this record
//Uses javascript to post page back
e.Row.Attributes["onmouseover"] = "this.style.cursor='hand';this.style.textDecoration='underline';";
e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";
e.Row.Attributes.Add("onclick", ClientScript.GetPostBackClientHyperlink(this.gvMainGrid, "Select$" + e.Row.RowIndex));
}
}
I am manually binding the gridview from a database and don't want to rebind the grid just to highlight the row, but I can't seem to add any javascript to the onclick event, it seems to either show the GetPostBackClientHyperlink or the row highlight javascript.
How to highlight gridview when row is selected
for this you have to write this code in your code behind file in OnRowCreated event or your can also write this code in OnRowDataBound event of grid...
protected void ctlGridView_OnRowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onclick", "onGridViewRowSelected('" + e.Row.RowIndex.ToString() + "')");
}
}
and add this one script
<script language="javascript" type="text/javascript">
var gridViewCtlId = '<%=ctlGridView.ClientID%>';
var gridViewCtl = null;
var curSelRow = null;
function getGridViewControl()
{
if (null == gridViewCtl)
{
gridViewCtl = document.getElementById(gridViewCtlId);
}
}
function onGridViewRowSelected(rowIdx)
{
var selRow = getSelectedRow(rowIdx);
if (curSelRow != null)
{
curSelRow.style.backgroundColor = '#ffffff';
}
if (null != selRow)
{
curSelRow = selRow;
curSelRow.style.backgroundColor = '#ababab';
}
}
function getSelectedRow(rowIdx)
{
getGridViewControl();
if (null != gridViewCtl)
{
return gridViewCtl.rows[rowIdx];
}
return null;
}
</script>
and it will highlight the selected row..
I was struggling to add both on click events to the row databound:
e.Row.Attributes.Add("onclick", ClientScript.GetPostBackClientHyperlink(this.gvMainGrid, "Select$" + e.Row.RowIndex));
e.Row.Attributes.Add("onclick", "onGridViewRowSelected('" + e.Row.RowIndex.ToString() + "')");
Appending the PostBack select after the row highlight method with ';' seems to have worked.
e.Row.Attributes.Add("onclick", "onGridViewRowSelected('" + e.Row.RowIndex.ToString() + "');" + ClientScript.GetPostBackClientHyperlink(this.gvMainGrid, "Select$" + e.Row.RowIndex));
Firstly, you can't apply text-decoration to a <tr>... or a <td> for that matter. You need to apply it to the elements inside.
Here are a couple adjustments you can try-
e.Row.Attributes.Add("onmouseover", "this.style.cursor='hand';";
e.Row.Attributes.Add("onclick", ClientScript.GetPostBackClientHyperlink(this.gvMainGrid.ClientId, "Select$" + e.Row.RowIndex));
The 1st works for me in code. Didn't have anything handy to test the 2nd.
Related
The cancel button of the gridview is not working when the delete button is set to disabled by the C# code (delete button is set to disabled if lbltype.Text != admin). So when I click on edit I cannot cancel the edit because the button is disabled See the Gridview image below
C# Code
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
lbltype.Text = Session["Type"].ToString();
DataRowView drv = e.Row.DataItem as DataRowView;
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (lbltype.Text != "admin")
{
LinkButton editLink = (LinkButton)e.Row.Cells[6].Controls[2];
editLink.Enabled = false;
}
}
if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex != GridView1.EditIndex)
{
(e.Row.Cells[6].Controls[2] as LinkButton).Attributes["onclick"] = "return confirm('Do you want to delete this row?');";
}
}
So while fooling around with webforms, I tried to create a page that outputs a table from a sql server to a html table on Page_Load. I then tried to add a button to a column which would redirect to a page. The only problem is, when I press the button nothing happens at all... I've tried putting breakpoints at the onclick method but they are never reached.
num = ds.Tables[0].Rows.Count;
htmlTable.Append("<tr style='background-color:#bd0000; color: White;'><th>ID</th><th>Job #</th><th>Project</th><th>Completed By</th><th>Date Created</th><th></th></tr>");
if (!object.Equals(ds.Tables[0], null))
{
if (ds.Tables[0].Rows.Count > 0)
{
int MAX_VIEW = (ds.Tables[0].Rows.Count > 15) ? 15 : ds.Tables[0].Rows.Count;
for (int i = 0; i < MAX_VIEW; i++)
{
htmlTable.Append("<td>" + ds.Tables[0].Rows[i]["CCPOF_ID"] + "</td>");
htmlTable.Append("<td>" + ds.Tables[0].Rows[i]["Job_Number"] + "</td>");
htmlTable.Append("<td>" + ds.Tables[0].Rows[i]["Project_Name"] + "</td>");
htmlTable.Append("<td>" + ds.Tables[0].Rows[i]["CompletedBy"] + "</td>");
htmlTable.Append("<td>" + ds.Tables[0].Rows[i]["DateCreated"] + "</td>");
htmlTable.Append("<td width=\"10%\"><button class=\"astext\" name=\"Btn" + ds.Tables[0].Rows[i]["CCPOF_ID"] + "\" id =\"" + ds.Tables[0].Rows[i]["CCPOF_ID"] + "\" OnClick =\"btnEdit_Click\" runat=\"server\" >Edit</button> | Details</td>");
htmlTable.Append("</tr>");
}
htmlTable.Append("</table>");
DBDataPlaceHolder.Controls.Add(new System.Web.UI.WebControls.Literal { Text = htmlTable.ToString() });
}
else
{
htmlTable.Append("<tr>");
htmlTable.Append("<td align='center' colspan='4'>There is no Record.</td>");
htmlTable.Append("</tr>");
}
}
}
protected void btnEdit_Click(object sender, EventArgs e)
{
String id = ((System.Web.UI.WebControls.Button)sender).ID;
Server.Transfer("CcpofDetails.aspx?ID=" + id);
}
}
When I inspect the button in the live form this is what I see
<button class="astext" name="Btn10" id="10" onclick="btnEdit_Click" runat="server">Edit</button>
Your way of generating dynamic controls seems very strange to me. It is not the way web-forms work.
To run an event on a control, it has to be loaded into servers memory first. But you are just filling some html text that is understandable only for the browser, not for asp.net engine.
take a look at this sample
To give you a better idea, create your buttons like this
private void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack)
AddControls();
}
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
if (ViewState["controsladded"] == null)
AddControls();
}
private void AddControls()
{
TextBox dynamictextbox = new TextBox();
dynamictextbox.Text = "(Enter some text)";
dynamictextbox.ID = "dynamictextbox";
Button dynamicbutton = new Button();
dynamicbutton.Click += new System.EventHandler(dynamicbutton_Click);
dynamicbutton.Text = "Dynamic Button";
Panel1.Controls.Add(dynamictextbox);
Panel1.Controls.Add(new LiteralControl("<BR>"));
Panel1.Controls.Add(new LiteralControl("<BR>"));
Panel1.Controls.Add(dynamicbutton);
ViewState["controlsadded"] = true;
}
private void dynamicbutton_Click(Object sender, System.EventArgs e)
{
TextBox tb = new TextBox();
tb = (TextBox) (Panel1.FindControl("dynamictextbox"));
Label1.Text = tb.Text;
}
I believe your problem comes from the fact that ASP.NET doesn't know you created a button. As far as it's concerned, all you did was pump out some text to the page.
As a result, when you post back to the server, it doesn't know it needs to do anything on the server side when you click.
Try creating it as an object (a System.Web.UI.WebControls.Button) and adding that to your page's Controls collection. Be aware that you'll have to do this both on the initial page build and on postback: if the control doesn't exist after postback, events that were hooked up to it don't fire.
Getting it to appear in the middle of your table may require you to do your HTML table creation in some other way, such as building a WebControls Table object and adding that to your Controls collection.
You are not adding corectl the button to the web form. Try this way:
Button btnEdit = New Button();
btn.Edit.Click += btnEdit_Click;
frmMain.Controls.Add(btnSave)
As shown in this question too.
I have a button click that will generate the text from gridview cells. But I want to remove the href tag when it get the text. How can I do it? Trying to do .atrributes.remove("href) but can't get it to save to a arraylist
protected void Button_Example_Click(object sender, EventArgs e)
{
foreach (GridViewRow s in GridView_Staff.Rows)
{
CheckBox CheckBox_Staff = (s.FindControl("CheckBox_Staff") as CheckBox);
if (CheckBox_Staff.Checked == true)
{
s.Cells[2].Attributes.Remove("href");
Response.Write("<script>alert('" + s.Cells[2].Text + "');</script>");
}
}
}
s.Cells[2].Text contains:
Example A
It's been a while since I was last using webforms and GridView, but to my eye it looks as though you are calling .Attributes.Remove() on the Cell object itself (.Cells[2]). But I would have thought that the anchor tag was inside the cell?
Would it not be more like this (excuse the pseudo-code):
var Anchor = s.Cells[2].FindControl("TheAnchor") as AnchorTag;
Anchor.Attributes.Remove("href");
Response.Write("<script>alert('" + Anchor.Text + "');</script>");
Or something similar?
You could use a regular expression to remove the href attribute like this:
protected void Button_Example_Click(object sender, EventArgs e)
{
foreach (GridViewRow s in GridView_Staff.Rows)
{
CheckBox CheckBox_Staff = (s.FindControl("CheckBox_Staff") as CheckBox);
if (CheckBox_Staff.Checked == true)
{
string text = s.Cells[2].Text;
string pattern = #"(?<=<[^<>]+)\s+(?:href)\s*=\s*([""']).*?\1";
text = System.Text.RegularExpressions.Regex.Replace(text, pattern, "", RegexOptions.IgnoreCase);
s.Cells[2].Text = text;
Response.Write("<script>alert('" + s.Cells[2].Text + "');</script>");
}
}
}
I've a gridview with selected columns and rows. The row consists of Textbox for every column in a row. I need to select a row in order to get the current rowindex which I've done using below code.
protected void gvtotqty_onrowdatabound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onclick"] = Page.ClientScript.GetPostBackClientHyperlink(gvtotqty, "Select$" + e.Row.RowIndex);
e.Row.ToolTip = "Click to select this row.";
}
}
protected void gvtotqty_onselectedindexchanged(object sender, EventArgs e)
{
foreach (GridViewRow row in gvtotqty.Rows)
{
if (row.RowIndex == gvtotqty.SelectedIndex)
{
Session["rowindex"]=row.RowIndex;
row.BackColor = ColorTranslator.FromHtml("#A1DCF2");
row.ToolTip = string.Empty;
}
else
{
row.BackColor = ColorTranslator.FromHtml("#FFFFFF");
row.ToolTip = "Click to select this row.";
}
}
}
Everything is working fine where I get my rowindex when debugged but I am not able to type anything in Textbox as it is getting refreshed. I know that
Page.ClientScript.GetPostBackClientHyperlink
calls PostBackEvent. By using this method, how can I type the values in Textboxes?
Try with this line of code
e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink((Control)sender, "Select$" + e.Row.RowIndex);
instead of your
e.Row.Attributes["onclick"] = Page.ClientScript.GetPostBackClientHyperlink(gvtotqty, "Select$" + e.Row.RowIndex);
if it doesn't work try putting your grid inside an updatePanel and add the trigger for selected index change of your grid
<asp:UpdatePanel ID="uppan1" runat="server">
<ContentTemplate>
//yourGridView here with id=GridView1
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="GridView1" EventName="selectedIndexChanged"/>
</Triggers>
</asp:UpdatePanel>
and change your selected index change function in this way
protected void gvtotqty_onselectedindexchanged(object sender, EventArgs e)
{
foreach (GridViewRow row in gvtotqty.Rows)
{
if (row.RowIndex == gvtotqty.SelectedIndex)
{
Session["rowindex"]=row.RowIndex;
row.BackColor = ColorTranslator.FromHtml("#A1DCF2");
row.ToolTip = string.Empty;
row.Attributes["onclick"] = "";
}
else
{
row.BackColor = ColorTranslator.FromHtml("#FFFFFF");
row.ToolTip = "Click to select this row.";
row.Attributes["onclick"] = Page.ClientScript.GetPostBackClientHyperlink(gvtotqty, "Select$" + row.RowIndex);
}
}
}
As from your code I understand that you want to select the row and display the row in different color on selectedindex changed. If I am correct you can achieve this using the following method.
Add a button field, or template field, which contains a button with the command name "Select". Command name should be select.
<asp:ButtonField CommandName="Select" Text="Select"/>
Then for the grid view add SelectedRowStyle
<SelectedRowStyle BackColor="#A1DCF2" />
This should already select the row with differnt color. You dont need to write code for gvtotqty_onselectedindexchanged and gvtotqty_onrowdatabound
UPDATE
Based on your comment, since you may have multiple controls on the row, like textbox, link etc. then eventhough click the textbox to enter text, it does the postback and clears the content of the text.
I think you can use JavaScript for selecting row, instead of posting back as below.
<script type="text/javascript">
function selectRow(control) {
//Clear all the currently selected rows. change the scope, if you have multiple tables
$('tr').css("background-color", "#FFFFFF");
// Select the current row
$(control).css("background-color", "#A1DCF2");
}
</script>
Then add this function to the row in your onrowdatabound event
protected void gvtotqty_onrowdatabound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onclick"] = "selectRow(this);";
e.Row.ToolTip = "Click to select this row.";
}
}
I have referenced my javascript in my page as follows
<script src="JScript1.js" type="text/javascript"></script>
These are my function inside that script file
function multiplication(txtQuantity) {
var weight = document.getElementById(txtQuantity).value;
}
function f(sender, args) {
args.IsValid = false;
var gridview = document.getElementById("<%=Gridview1.ClientID%>");
var txt = gridview.getElementsByTagName("textarea");
for (i = 0; i < txt.length; i++) {
if (txt[i].id.indexOf("TextBox1") != -1) {
if (txt[i].value == '') {
args.IsValid = false;
}
else {
args.IsValid = true;
}
}
}
}
function f1(sender, args) {
args.IsValid = false;
var gridview = document.getElementById("<%=Gridview1.ClientID%>");
var txt = gridview.getElementsByTagName("textarea");
for (i = 0; i < txt.length; i++) {
if (txt[i].id.indexOf("TextBox2") != -1) {
if (txt[i].value == '') {
args.IsValid = false;
}
else {
args.IsValid = true;
}
}
}
}
I would like to call these function from my code behind and also I would like to assign the function to custom validator
I tried some thing as follows but not working
<asp:CustomValidator ID="custValCountry" runat="server" ValidationGroup="Country"
ValidateEmptyText="true" ControlToValidate="TextBox1" ClientValidationFunction="javascript:f"
ErrorMessage="Other is required"></asp:CustomValidator>
Also my under my RowDataBound event I write as follows this is also not working
protected void Gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
TextBox txt = (TextBox)e.Row.FindControl("TextBox1");
Page.ClientScript.RegisterClientScriptBlock(txt.GetType(), "onBlur", "multiplication('" + txt.ClientID + "')");
//Page.ClientScript.RegisterClientScriptBlock(, "Script", "alert('Records Successfuly Saved!');", true);
// txt.Attributes.Add("onBlur", "return javascript:multiplication('" + txt.ClientID + "');");
//TextBox txt1 = (TextBox)e.Row.FindControl("TextBox2");
txt1.Attributes.Add("onBlur", "return javascript:multiplication('" + txt1.ClientID + "');");
}
}
Can some one help me
Static JavaScript files do not get fed through ASP.NET normally, so this line will not work:
var gridview = document.getElementById("<%=Gridview1.ClientID%>");
Use a fixed ID for the grid and specify it directly:
var gridview = document.getElementById('my-grid');
<asp:GridView ID="my-grid" ClientIDMode="Static" runat="server" ...>
Or come up with some other way of finding the ID.
Also note that this function is next to worthless:
function multiplication(txtQuantity) {
var weight = document.getElementById(txtQuantity).value;
}
You get the weight then do nothing with it?
You need to realize that your javascript functions are running in the client's browser, not on your server where your code behind is running. If you need to call the functions from your code behind, you will need to create equivalent functions in your code behind.