I was working on asp.net GridView control. Now I need to edit some row data. For that I was using this code:
<asp:LinkButton ID="btnEdit" Text="Edit" runat="server" CommandName="QuickEdit" OnClick="btnEdit_Click"
CommandArgument ='<%# ((CheckBox)(((GridViewRow) Container).Cells[4].Controls[0])).Checked %>'/>
And the btnEdit_Click method is:
protected void btnEdit_Click(object sender,EventArgs e)
{
LinkButton btn = (LinkButton)sender;
switch (btn.CommandName)
{
case "QuickEdit":
EditPanel.Visible = true;
GridPanel.Visible = false;
CheckBox cbRequiresState = (CheckBox)EditPanel.FindControl("checkRequiresState");
if (btn.CommandArgument =="True")
{
cbRequiresState.Checked = true;
}
else
{
cbRequiresState.Checked = false;
}
break;
}
}
Now, I need to pass more than one argument as CommandArgument to that btnEdit_Click method. For that what I need to do?
And please suggest me a good way to utilize those arguments in that method.
here is an example :
in your aspx code :
<asp:ImageButton ID="btnSelect" runat="server" ImageUrl="~/Images/btnSelect.png" CommandName="Select" CommandArgument='<%# Container.DataItemIndex +";"+Eval("ID") %>' ToolTip="select" CausesValidation="False" /></ItemTemplate>
and in your code behind :
string info = e.CommandArgument.ToString();
string[] arg = new string[2];
char[] splitter = { ';' };
arg = info.Split(splitter);
You can use a string and separate the values by ; or another character.
Because CommandArgument is a simple string, concatenate the arguments you want to pass to the event putting some kind of separator among them.
Then in btnEdit_Click split the values by separator.
NOTE: Chose the sepatator so that it isn't a character contained in anyone of the parameters passed to the event.
Related
can we pass multiple eval field in one command argument.
my code is here
<asp:TemplateField HeaderText="Details" SortExpression="source">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CommandArgument='<%#Eval("source") %>' CommandName="Download" Text='<%#Eval("source") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
I want to be pass many Eval field in single command argument with command name
if possible please show any reference.
If this is what you are asking as you didnt provide any code snippet i'm assuming like this
CommandArgument='<%#Eval("ScrapId")+","+ Eval("UserId")%>'
In code behind you can use retrieve values like this
protected void GridViews_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Comment")
{
string[] commandArgs = e.CommandArgument.ToString().Split(new char[] { ',' });
string scrapid = commandArgs[0];
string uid = commandArgs[1];
}
}
You can do something like
<%# Eval("Param1").ToString() + Eval("Param2").ToString() %>
I have a couple of GridViews in my FormView page and I am wanting to make an Insert row in the FooterRow of the Gridviews. Layout and everything is fine. However, as I'm building the codebehind for the Insert command, I'm running into a context problem. If I move the GridView outside of the FormView markup, the context errors clear up immediately.
GridView Markup
<asp:GridView ID="gvBFMats" runat="server" ShowFooter="True" AutoGenerateColumns="False" DataKeyNames="MaterialID" DataSourceID="BFMatsSQL" OnRowCommand="gvBFMats_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Commands" ShowHeader="False">
<EditItemTemplate>
<asp:LinkButton ID="ButtonUpdate" runat="server" CausesValidation="True" CommandName="Update" Text="Update"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="ButtonEdit" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit"></asp:LinkButton>
<asp:LinkButton ID="ButtonDelete" runat="server" CausesValidation="False" CommandName="Delete" Text="Delete"></asp:LinkButton>
</ItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="ButtonAdd" runat="server" CommandName="Insert" Text="Add to Table" />
</FooterTemplate>
...
Insert Command Codebehind
protected void gvBFMats_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Insert" && Page.IsValid)
{
BFMatsSQL.Insert();
}
}
protected void BFMatsSQL_Inserting
(object sender, ObjectDataSourceMethodEventArgs e)
{
DropDownList ddlNewMfr =
(DropDownList)gvBFMats.FooterRow.FindControl("ddlNewMfr");
DropDownList ddlNewThickness =
(DropDownList)gvBFMats.FooterRow.FindControl("ddlNewThickness");
DropDownList ddlNewCore =
(DropDownList)gvBFMats.FooterRow.FindControl("ddlNewCore");
DropDownList ddlNewSize =
(DropDownList)gvBFMats.FooterRow.FindControl("ddlNewSize");
TextBox txtNewColor =
(TextBox)gvBFMats.FooterRow.FindControl("txtNewColor");
TextBox txtNewQty =
(TextBox)gvBFMats.FooterRow.FindControl("txtNewQty");
DropDownList ddlNewFinish =
(DropDownList)gvBFMats.FooterRow.FindControl("ddlNewFinish");
TextBox txtNewExtra =
(TextBox)gvBFMats.FooterRow.FindControl("txtNewExtra");
// Set the SQLDataSource's InsertParameters values
e.InputParameters["MatManufacturerID"] =
Convert.ToInt32(ddlNewMfr.SelectedValue);
e.InputParameters["MatThicknessID"] =
Convert.ToInt32(ddlNewThickness.SelectedValue);
e.InputParameters["MatCoreID"] =
Convert.ToInt32(ddlNewCore.SelectedValue);
e.InputParameters["MatSizeID"] =
Convert.ToInt32(ddlNewSize.SelectedValue);
e.InputParameters["MatFinishPrePostID"] =
Convert.ToInt32(ddlNewFinish.SelectedValue);
string strNewColor = null;
if (!string.IsNullOrEmpty(txtNewColor.Text))
strNewColor = txtNewColor.Text;
e.InputParameters["MatFinishColor"] = strNewColor;
int? intNewQty = null;
if (!string.IsNullOrEmpty(txtNewQty.Text))
intNewQty = Convert.ToInt32(txtNewQty.Text);
e.InputParameters["MatQty"] = intNewQty;
string strNewExtra = null;
if (!string.IsNullOrEmpty(txtNewExtra.Text))
strNewExtra = txtNewExtra.Text;
e.InputParameters["MatNumExtraSheets"] = strNewExtra;
}
Specifically, I get the red squiggly under the gvBFMats in the (Control)gvBFMats.FooterRow.FindControl("Control ID"); that says "The name 'gvBFMats' does not exist in the current context." I'm only guessing that it doesn't like the call to the GridView when it's nested inside a FormView template. Is there a way to pass this context along programatically?
You're right about it not recognizing the name gvBFMats because it's embedded in a template. Only "top-level", non-embedded controls will be treated in Code Behind as if they had been explicitly declared. Controls declared in a template will not. The compiler doesn't recognize those names.
There's a reason for this. Imagine you have a control called TextBox1 in one of the ItemTemplates for a repeating control. You bind it. Your page's control tree now has dozens of controls with the ID TextBox1. If you want to refer to TextBox1, how does it know which one you mean?
So. What can you do in your situation? Well, BFMatsSQL_Inserting and gvBFMats_RowCommand are both event handlers, so you can't change their signatures.
But, you can make use of them belonging to the same class, and use a module-level variable to hold the reference to gvBFMats. Like this:
private GridView gvBFMats;
protected void gvBFMats_RowCommand(object sender, GridViewCommandEventArgs e)
{
gvBFMats = [your form view].Row.FindControl("gvBFMats") as GridView;
if (e.CommandName == "Insert" && Page.IsValid)
{
BFMatsSQL.Insert();
}
}
Now, BFMatsSQL_Inserting will be able to refer to gvBFMats, and it should have a value.
I have one Repeater with multiple rows.each row has one LinkButton and one HiddenField.
HiddenField value is bind at time of Repeater's Event OnItemDataBound.
My Question is that How can I pass this HiddenField Field Value with CommandArgument of this LinkButton?
Following is my source code.
<asp:Repeater ID="rptServiceRequestList" runat="server" OnItemCommand="rptServiceRequestList_ItemCommand" OnItemDataBound="rptServiceRequestList_ItemDataBound">
<ItemTemplate>
<asp:LinkButton ID="btnCustomerDeposit" runat="server" Text="Pay Deposit" CommandName="DepositFees" CommandArgument='<%# Eval("ServiceRequestId") %>'>
</asp:LinkButton>
<asp:HiddenField ID="hidAmount" runat="server" />
</asp:Repeater>
Please Help me. thank you to all in advance.
Yes you can set multiple command argument or the another way is you can use FindControl("hidAmount") method of repeater .
You can use below code.
HiddenField hdnAmount = (HiddenField)rptServiceRequestList.FindControl("hidAmount");
int amnt = Convert.ToInt32(hdnAmount.Value);
You can set multiple command argument(to send hidamount along with command Argument) as:
<asp:LinkButton ID="btnCustomerDeposit" runat="server" Text="Pay Deposit" CommandName="DepositFees" CommandArgument='<%#Eval("ServiceRequestId") + "|" +Eval("HidAmount")%>'
</asp:LinkButton>
And on ItemCommand:
protected void rptServiceRequestList_ItemDataBound(Object Sender, RepeaterCommandEventArgs e)
{
string[] arg = new string[2];
arg = e.CommandArgument.ToString().Split('|'); // Split Here to seprate CommandName And Hidden Value
string YourcommandName = arg[0]; // Your Command Name
string YourHiddenValue = arg[1]; // Your Hidden Field Value
}
I have a Gridview dtAppend. I want that when I press delete button the selected row record should be deleted from users table.
I first used button field in gridview, as:
<asp:ButtonField Text="Delete" CommandName="DeleteRow" ControlStyle-CssClass="btn btn-danger btn-small" ControlStyle-ForeColor="White" />
<asp:TemplateField visible="false" ItemStyle-Width="0px">
<ItemTemplate>
<asp:HiddenField ID="HiddenField" Visible="false" runat="server" Value='<%# Eval("userId") %>' />
</ItemTemplate>
</asp:TemplateField>
My client says to show JavaScript alert and on clicking yes the record should be deleted. I cannot write onClientClick for button field so I am being forced to use normal Asp button.
on rowCommand of gridview I am getting the hidden field value in this code
if (e.CommandName == "DeleteRow")
{
GridViewRow row = dtAppend.Rows[Convert.ToInt32(e.CommandArgument)];
hidden1 = (HiddenField)row.Cells[6].FindControl("HiddenField");
string text = Convert.ToString((HiddenField)row.Cells[6].FindControl("HiddenField"));
Session["dtIdDel"] = hidden1.Value;
}
i am getting thew value in Session but i need above code working Button_ClickEvent like below
protected void deleteButton_Click(object sender, EventArgs e)
{
GridViewRow row = dtAppend.Rows[Convert.ToInt32(e.CommandArgument)];
hidden1 = (HiddenField)row.Cells[6].FindControl("HiddenField");
string text = Convert.ToString((HiddenField)row.Cells[6].FindControl("HiddenField"));
Session["dtIdDel"] = hidden1.Value;}
this is where 'e.CommandArgument' gives Error
I cannot use the above code in normal button click as it gives error in e.CommandArgument
Any help?
Simply you can remove visible="false"
<asp:HiddenField ID="HiddenField" runat="server" Value='<%# Eval("userId") %>' />
You Better Remove Visible="false" . Because, the value that has to be binded for hidden field will not be binded in to the field if Visible="false" is there. Any how its a hidden field, so make it Visible="true"
EDIT :
How you handled the RowDataBound event of the Grid, are you assigning the CommandArgument for each row, other wise the above concept will not work in Paging. Refer as below
Ex : -
Button btnMail = (Button)e.Row.FindControl("lnkMail");
btnMail.CommandArgument = e.Row.RowIndex.ToString();
I think this would be easy way, instead of using hidden field.
<asp:LinkButton CommandArgument='<%# Eval("userId") %>' OnClientClick="if (!confirm('Are you sure you want delete?')) return false;" CommandName="DeleteRow" ID="eliminar" runat="server" Text="delete"/>
if (e.CommandName == "DeleteRow")
{
int userId = Int32.Parse(e.CommandArgument.ToString());
}
You can simply send ID as command argument
or
Try the code as below:
var ID = int.Parse(((HiddenField)item.FindControl("HiddenField1")).Value);
sql = "delete from tablename where id=" + ID;
I have an ImageButton control as part of a GridView control that is displayed as an ItemTemplate and in the same GridView. I have a regular Button control to which I added some code like this
if (e.CommandName == "addToSession")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow selectedRow = ((GridView)e.CommandSource).Rows[index];
string ISBN = selectedRow.Cells[0].Text;
string bookTitle = selectedRow.Cells[1].Text;
string image = selectedRow.Cells[2].Text;
//storing title, author, pictureUrl into session variables to 'carry them over' to RateBook.aspx
Service s = new Service();
Session["ISBN"] = ISBN;
Session["bookTitle"] = bookTitle;
Session["ImageUrl"] = s.returnImageUrl(bookTitle);
if (Session["userName"] == null)
{
Response.Redirect("registerPage.aspx");
}
else
{
Response.Redirect("RateBook.aspx");
}
}
else if (e.CommandName == "ratedBooks")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow selectedRow = ((GridView)e.CommandSource).Rows[index];
string bookTitle = selectedRow.Cells[1].Text;
Service s = new Service();
Session["ImageUrl"] = s.returnImageUrl(bookTitle);
Response.Redirect("BookRated.aspx");
}
when I run this code I get a format exception and again I am not sure why. I have altered the image button a bit and nested the image in a link button which seems to be more correct.
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="ratedBooks">
<asp:Image ID="ImageButton1" ImageUrl='<%#Eval("pictureUrl") %>' runat="server" />
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
Please advise.
Regards,
Arian
I believe you can accomplish your needs with an ImageButton, as it supports all the major Button functionality, including CommandName (see http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.imagebutton.commandname.aspx).
Try this out:
<asp:ImageButton ID="LinkButton1" runat="server"
CommandName="ratedBooks"
ImageUrl='<%#Eval("pictureUrl") %>' />
Also, note that your format exception could be coming from the lines that read:
Convert.ToInt32(e.CommandArgument);
The reason being that there appears from this code snippet to be no value assigned to the CommandArgument of the button. Convert.ToInt32 requires a valid integer value to be passed in, which means that the ImageButton needs to have a number bound to its CommandArgument property.
If you based your solution on this MSDN reference (http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridviewcommandeventargs.aspx), note that the <asp:ButtonField> column type gets special treatment; the CommandArgument is set to the row index. When you use a template field, ASP.NET requires you to specify or data bind your own command argument.
Update
This question contains details on binding the grid view row index to a custom button:
ASP.NET GridView RowIndex As CommandArgument
A possible solution is to add the ItemDataBound event handler and search for the image button change its image url.
MyGrid.RowDataBound += new RepeaterItemEventHandler(MyGrid_RowDataBound);
void MyGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex > -1)
{
ImageButton image = e.Row.FindControl("MY_IMAGE_CONTROL") as ImageButton;
image.ImageUrl = "PATH_TO_IMAGE";
}
}
Hope it helps.
You need CommandArgument
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:ImageButton ID="ImageButton1" runat="server" CommandName="Delete" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" ImageUrl="~/Modelos/Img/deleted.gif" />
</ItemTemplate>
</asp:TemplateField>
code behind C#
public void GridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
string t;
if (e.CommandName == "Delete")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow selectedRow = grid1.Rows[index];
t = selectedRow.Cells[2].Text;
}
}
On ASPX
<asp:GridView ID="grid1" runat="server" onselectedindexchanged="GridView1_SelectedIndexChanged" ...