Get a value of checked checkbox into a button from a Gridview - c#

I have a Gridview Generated as follows :
<asp:GridView ID="Cash_GridView" runat="server" CssClass="Grid" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="MemberCheck" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Loan_Acno" HeaderText="Loan A/C number" />
</Columns>
</asp:Gridview>
<asp:Button ID="CashPayButton" runat="server" Text="Pay Dividend" CssClass="bluesome" OnClick="CashPayButton_Click" />
And also having the above button click event now when i click checkbox on particular row i want that whole row to be get caluclated in the Button click event in the code behind
protected void CashPayButton_Click(object sender, EventArgs e)
{ }

Is this what you want?
protected void CashPayButton_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in Cash_GridView.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox c = (CheckBox)row.FindControl("MemberCheck");
if (c.Checked)
{
//do calculation with other controls in the row
}
}
}
}
(or should the calculation happen immediately on clicking the checkbox, than this will not work)

Assuming that's the only button you will have to click to do your calculations, you can do the following (note that I'm using the Load event), it will be called when you click your button and when the postback occurs.
(Calculation will happen when you click the button because of the postback)
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
ProcessRows();
}
}
private void ProcessRows()
{
foreach (GridViewRow oneRow in Cash_GridView.Rows)
{
CheckBox checkBoxControl = oneRow.FindControl("MemberCheck") as CheckBox;
if (checkBoxControl != null && checkBoxControl.Checked)
{
// You have a row with a 'Checked' checkbox.
// You can access other controls like I have accessed the checkbox
// For example, If you have a textbox named "YourTextBox":
TextBox textBoxSomething = oneRow.FindControl("YourTextBox") as TextBox;
if (textBoxSomething != null)
{
// Use the control value for whatever purpose you want.
// Example:
if (!string.IsNullOrWhiteSpace(textBoxSomething.Text))
{
int amount = 0;
int.TryParse(textBoxSomething.Text, out amount);
// Now you can use the amount for any calculation
}
}
}
}
}

Use the following code:
protected void CashPayButton_Click(object sender, EventArgs e)
{
foreach(Gridviewrow gvr in Cash_GridView.Rows)
{
if(((CheckBox)gvr.findcontrol("MemberCheck")).Checked == true)
{
int uPrimaryid= gvr.cells["uPrimaryID"];
}
}
}

foreach (GridViewRow r in GridView1.Rows)
{
if ((r.Cells[2].Controls.OfType<CheckBox>().ToList()[0]).Checked == true)
{
//your code.
}
}

Related

Hidden edit button in GridView using C#

I have entered this condition in my dataset
when the value of message is equal to "1" it is not possible to continue working on this webpage...
when the value of message is equal to "0" it's possible to continue but it's not possible to edit the gridview data...
My code below
if (message == 1)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "Alert", "alert('test msg 1');window.location='Default.aspx';", true);
return null;
}
else if (message == 0)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "Alert", "alert('test msg 2');", true);
btrila.Visible = false;
btnreset.Visible = true;
return dsProducts;
}
else
{
return dsProducts;
}
when the value of message is equal to "0" I need hidden or disable the button below for edit the gridview data
<ItemTemplate>
<asp:ImageButton ID="btnedit" runat="server"
CommandName="Edit"
ImageUrl="/aspnet/img/edit_icon.gif"
ToolTip="Edit" />
</ItemTemplate>
I have tried this solution in RowDataBound without success because the "btnedit" is always hidden...
Any help would greatly appreciate... Thank you.
protected void gvProducts_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.DataItem != null)
{
if (btnreset.Visible == true)
{
gvProducts.Columns[2].Visible = false;
}
else
{
gvProducts.Columns[2].Visible = true;
}
}
}
}
when the value of message is equal to "0" I need hidden or disable the
button below for edit the gridview data
on the DataBound function you need to loop the cells and locate your control - here is how
protected void onRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// loop all data rows
foreach (DataControlFieldCell cell in e.Row.Cells)
{
// check all cells in one row
foreach (Control control in cell.Controls)
{
// go to find this button
Button button = control as Button;
if (button != null && button.CommandName == "Edit")
button.Enable = false; // or true depend on your contitions.
}
}
}
}

unable to find edit template control checkbox in row command

I tried to get the control of edit template which is checkbox in row command event but I am unable to get it, but I am getting label control which is in row index.
I tried the above below code to get the control:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
GridViewRow gvr = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
Label icllbl = (Label)GridView1.Rows[gvr.RowIndex].FindControl("icllbl");
CheckBox iclcb = (CheckBox)GridView1.Rows[gvr.RowIndex].FindControl("iclcb");
if (e.CommandName.Equals("Edit"))
{
if (icllbl.Text == "Y")
{
iclcb.Checked = true;
}
}
}
And I tried RowDataBound event also luckily I am getting checkbox control here but this time I am unable to get the Label control in below code:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label icllbl = (Label)e.Row.FindControl("icllbl");
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
CheckBox iclcb = (CheckBox)e.Row.FindControl("iclcb");
if (icllbl.Text == "Y")
{
iclcb.Checked = true;
}
}
}
}
Please correct me if I am wrong anywhere.
Thanks in advance!
In your RowCommand event use control class to cast into GridViewRow:
GridViewRow row = (GridViewRow)(((Control)e.CommandSource).NamingContainer);
int rowIndex = row.RowIndex;
And in RowDataBound event place Label control inside Edit (check for EditTemplate) check:
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
Label icllbl = (Label)e.Row.FindControl("icllbl");
CheckBox iclcb = (CheckBox)e.Row.FindControl("iclcb");
//... other code of lines will be here
}

Button Inside a grid value is not returning updated value onclick event

I have a Button inside an ItemTemplate in a grid. I'm assigning the button text dynamically. Since I need to have different text for each row button. But OnClick event is not showing the updated text instead it is showing a empty string. Please help!!
<asp:TemplateField HeaderText="GetHistory">
<ItemTemplate>
<asp:Button
DataField="GetHistory"
ID="btn_getHistory"
CausesValidation="false"
runat="server"
OnClick="btn_getHistory_Click" Visible="false" />
</ItemTemplate>
</asp:TemplateField>
protected void btn_getHistory_Click(object sender, EventArgs e)
{
//My sender text is showing empty here
}
protected void GridViewTree1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && e.Row.DataItem != null && !((System.Data.DataRowView)(e.Row.DataItem)).Row.ItemArray[0].ToString().Contains("\\"))
{
Button btn_getHistory = (Button)e.Row.Cells[3].FindControl("btn_getHistory");
if (btn_getHistory != null)
{
btn_getHistory.Visible = true;
var chunks = ((System.Data.DataRowView)(e.Row.DataItem)).Row.ItemArray[0].ToString().Split('_'); // any separator characters
var a = chunks.Take(chunks.Length - 1);
string testsetName = string.Empty;
foreach (string b in a)
{
testsetName = testsetName + b + '_';
}
btn_getHistory.Text = testsetName.ToString().TrimEnd('_');
}
}

How to enable button based on gridview value?

I have a column in SQL:
Status
open
Close
and Gridview with Boundfield value='Status'
When a user selects a row and the Status == open then it should display a button. Otherwise ist hiden.
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
string y = Data.Rows[GridView1.SelectedIndex][5].ToString();
if (y == "open")
{
btnAccept.Visible = true;
}
else
{
btnAccept.Visible = false;
}
}
<asp:Button Text="Accept" OnClick="btnAccept_Click" Visible="false" ID="btnAccept" runat="server" />
This could be the solution:
string y = GriView1.SelecteRows[0].Cells[5].Value.ToString();
Modify your code like this
string y = GridView1.SelectedRow.Cells[5].Text;
It's counter-intuitive, but GridView1.SelectedRow is not set until after SelectedIndexChanged completes.
Also visibility has nothing to do with the button being Enabled or Disabled.
Use the Enabled Property of the Button:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridView gv = (GridView) sender ;
btnAccept.Enabled = (gv.Rows[ gv.SelectedIndex ].Cells[5].Text == "open");
}
Also, if you haven't already, consider styling disabled buttons with CSS:
input[type=button][disabled],
button[disabled]
{
cursor:not-allowed;
}

Get the value of Label in listview

I have a listview with invisible label to store the category Id.
what I want to do is to assign the text of the label to a cookie or session on button click.
the problem is my cookie is always null when I try to display the value outside the listview.
here is my aspx code:
<asp:ListView runat="server" ID="catListView" DataSourceID="CategoriesDataSource" >
<EmptyDataTemplate>No DataFound</EmptyDataTemplate>
<ItemTemplate>
<div class="service" style="margin-bottom:10px;width:230px;">
<h4 style="font-family:Corbel;" ><%#Eval("CatName") %></h4>
<asp:Label runat="server" Visible="false" ID="lblcat"><%#Eval("CatId") %></asp:Label>
<asp:Button runat="server" ID="btnTest" Text="View Items" OnClick="btnTest_Click" />
</div>
</ItemTemplate>
</asp:ListView>
my C# code:
protected void btnTest_Click(object sender, EventArgs e)
{
Response.Cookies["cat"].Value = "test";
foreach (ListViewItem item in catListView.Items)
{
Label catLabel = (Label)item.FindControl("lblcat");
Response.Cookies["cat"].Value = catLabel.Text.ToString();
}
}
any help will be appreciated.
thx in advance
Sam
It sounds like your ListView might not be databound when your Button click event is called.
I would recommend that you use the ItemCommand event handler. It is most appropriate for this type of handling. Update your ListView declaration to handle that event:
<asp:ListView runat="server" ID="catListView" DataSourceID="CategoriesDataSource
OnItemCommand="catListView_ItemCommand" >
Note: Don't forget to remove the "OnClick" event handler from the Button
And then write your even handler code like this:
protected void catListView_ItemCommand(object sender, ListViewCommandEventArgs e)
{
Label catLabel = (Label)e.Item.FindControl("lblcat");
Session["currentCatLabelText"] = catLabel.Text;
}
This also has the advantage of not looping through all your ListView items, but just looking at the one you clicked.
Hope this helps :)
string[] catvals = new string[catListView.Items.Count];
for (int i =0; i< catListView.Items.Count; i++)
{
Label catLabel = (Label)catListView.FindControl("lblcat");
catvals[i] = catLabel.Text;
}
for(int i = 0 ; i < catvals.Length; i++)
{
Response.Cookies["cat"+ i.ToString()].Value = catvals[i].ToString();
}
Actually you are trying to add your cat in one key. I mean you are overwriting values in loop.
You should change your code in this way:
In your C# code:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
HttpCookie testCokkie = new HttpCookie("ExampleCookie");
testCokkie.Expires = DateTime.Now.AddDays(5);
Response.Cookies.Add(testCokkie);
}
}
protected void btnTest_Click(object sender, EventArgs e)
{
HttpCookie ExampleCookie = Request.Cookies["ExampleCookie"];
int tempIndex = 0;
foreach (ListViewItem item in catListView.Items)
{
Label catLabel = (Label)item.FindControl("lblcat");
ExampleCookie["cat" + tempIndex.ToString()] = catLabel.Text.ToString();
tempIndex = tempIndex + 1;
}
}
TO read this cookie
HttpCookie exampleCookie = Request.Cookies["ExampleCookie"];
if (exampleCookie != null)
{
int tempIndex = 0;
foreach (ListViewItem item in catListView.Items)
{
Response.Write("<br/>" + exampleCookie["cat" + tempIndex.ToString()]);
tempIndex = tempIndex + 1;
}
}

Categories