ASP.net C# Bind Gridview using a button inside modalpopup - c#

Codes of the button inside modalpopup (
protected void btnYes_Click(object sender, EventArgs e)
{
int index = Convert.ToInt32(gvItemAssignment.SelectedRow.Cells[1].Text);
con.Close();
con.Open();
SqlCommand delete = new SqlCommand("UPDATE tblAssignment SET AssignDeleteStatus = 'Deleted' WHERE AssignID = " + index + "", con);
delete.ExecuteNonQuery();
con.Close();
dgvItemAssignment.DataBind();
btnDelete_ModalPopupExtender.Hide();
}
Modalpopup
<asp:ModalPopupExtender ID="btnDelete_ModalPopupExtender" runat="server"
BackgroundCssClass="modalBackground" CancelControlID="btnNo"
PopupControlID="Panel3" TargetControlID="btnRemove">
</asp:ModalPopupExtender>
btnRemove for calling (no codes inside)
Main problem is the Databind on btnYes is not working. Gridview is outside. ill click remove button then the popup shows. Then click btnYes inside, doing all the codes except databind, then popup hides. Tried doing this.Databind(); and also IsPostback on the PageLoad. Very much appreciated if you could help me with this. Stuck in a while.

Related

I'm Having an Issue with Panels c#

I have two pages:
Drop Down List that User picks a Customer Name from and a load button (Panel 1)
Page with Customer Order Information (Panel 2)
On the 2nd page, I have a check box that will show Customer Details in a DetailsView if it is checked.
My issue is when I go to click on the check box, it brings me back to my First Page with the DownDrop List, which is Panel 1. I have to click the load button to see the second panel again and once it's clicked again, it shows the DetailsView which the check box checked.
I have tried everything, this is what my code looks like:
protected void Page_Load(object sender, EventArgs e)
{
// always show first panel when page loads
pnlFirstPage.Visible = true;
pnlSecondPage.Visible = false;
}
protected void btnLoadOrders_Click(object sender, EventArgs e)
{
// hide the first page and continue to second page
pnlSecondPage.Visible = true;
pnlFirstPage.Visible = false;
// if statement to show details view of customer details
if (cbCustomerDetails.Checked == true)
{
dvCustomerDetails.Visible = true;
dvCustomerDetails.DataBind();
pnlFirstPage.Visible = false;
pnlSecondPage.Visible = true;
}
Ok, so the issue/problem is that keep in mind that EVERY post-back will trigger the page load event.
In other words, any button any dropdown/combo box, or ANY code event that triggers a post-back will fire the page load even EACH time, and THEN your button/event code stub runs.
Thus, for really what amounts to the last 200+ web form pages I built?
EVERY page for setup/loading controls, data etc. will have a if not postback code stub on the page load command.
So, say this markup in panel1
<asp:Panel ID="Panel1" runat="server">
<h3>Select Hotel</h3>
<asp:DropDownList ID="cboHotels" runat="server"
DataValueField="ID"
DataTextField="HotelName" Width="198px">
</asp:DropDownList>
<button runat="server" id="btnRun" title="Search"
style="margin-left: 15px"
type="button" class="btn"
onserverclick="btnRun_ServerClick">
<span class="glyphicon glyphicon-home"></span>View
<br />
</button>
</asp:Panel>
<asp:Panel ID="Panel2" runat="server" >
<h3>Hotel Infomration</h3>
<div id="EditRecord" runat="server"
style="float:left;display: normal;border:solid 2px;padding:12px;border-radius:12px">
<h2>Edit Hotel</h2>
<div style="float:left" class="iForm">
<label>HotelName</label>
<asp:TextBox ID="txtHotel" runat="server" f="HOtelName" width="280" /> <br />
bla bla bla for panel2.
so, now my code on startup can be to load up the combo box/dropdown list, and set Panel 1 visible, and panel 2 visible = false.
We have this code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Panel1.Visible = true;
Panel2.Visible = false;
LoadData(); // load our combo box
}
}
void LoadData()
{
SqlCommand cmdSQL =
new SqlCommand("SELECT ID, HotelName FROM tblHotelsA ORDER BY HotelName");
cboHotels.DataSource = MyRstP(cmdSQL);
cboHotels.DataBind();
cboHotels.Items.Insert(0, new ListItem("Select", ""));
}
DataTable MyRstP(SqlCommand cmdSQL)
{
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (cmdSQL)
{
cmdSQL.Connection = conn;
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
And the button to view the details (in panel2), then can look like this:
protected void btnRun_ServerClick(object sender, EventArgs e)
{
if (cboHotels.SelectedIndex > 0)
{
string strSQL = "SELECT * FROM tblHotelsA WHERE ID = #ID";
SqlCommand cmdSQL = new SqlCommand(strSQL);
cmdSQL.Parameters.Add("#ID", SqlDbType.Int).Value = cboHotels.SelectedItem.Value;
DataTable rstData = MyRstP(cmdSQL);
General.FLoader(EditRecord, rstData.Rows[0]);
Panel1.Visible = false;
Panel2.Visible = true;
}
}
And now the results are this:
So, just keep in mind that the REAL first page load has to be inside of that if !IsPostBack stub.
You can think of that code stub the REAL or "first" page load. Thus, loading up a gridview, loading up a combo box, and say setting panel1 visible, and panel2 hidden all typical code that one would place in the real page startup code.
It quite much means you can't really build a working page without taking into account that page-load fires each and every time a event occurs on the page.
In fact, if you adopt a up-date panel, then the above will holds true.

Attaching a click event onto an image within a grid view

I am having trouble attaching a click event onto an image that I have stored within a grid view. Basically it is a delete button that will allow the user to delete a specific row depending on where the button is. I have the code in c# ready for it, however, I cannot seem to attach a click event to it.
This is the markup code of the button
<asp:TemplateField HeaderText="Remove" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:ImageButton ID="imgbDeleteP" runat="server" BORDER="0" CausesValidation="false" ImageUrl="~/img/Del.png" Height="25px" ImageAlign="Middle"
onClick ="gv_Quals_RowCommand" CommandArgument="<%#Container.DataItemIndex%>" CommandName="Remove" />
</ItemTemplate>
onClick ="gv_Quals_RowCommand"
Here is the code in c# for the click event
protected void gv_Quals_RowCommand(object sender, GridViewCommandEventArgs e)
{
if ((e.CommandName == "Remove"))
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = gv_Quals.Rows[index];
DataTable dtCurrentTable = (DataTable)Session["CurrentTable"];
dtCurrentTable.Rows[index].Delete();
if ((dtCurrentTable.Rows.Count < 0))
{
}
else if ((row.Cells[0].Text != "*New*"))
{
int appId = 5000;
//int appId = 1;
string insProg = ("delete from projectunitassignment where UnitId =" + int.Parse(row.Cells[0].Text));
SqlCommand cmd = new SqlCommand(insProg, conn);
cmd.Connection.Close();
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
RebindCat(appId);
}
}
}
This is the compilation error that I keep getting
CS0123: No overload for 'gv_Quals_RowCommand' matches delegate 'ImageClickEventHandler'
I cannot set the click event through the properties as it is stored within the grid view so I cannot access it through there. Also the click event does not run as I have tested with debugging
The problem is with GridViewCommandEventArgs should be just EventArgs
public void imgbDeleteP_Click(object sender, EventArgs e)
Edit:
I see that in your code you use the Command Argument, so if you want to use that you should see this post
Basically use onCommand instead of onClick or cast the sender to button to get the command argument, something like:
var argument = ((ImageButton)sender).CommandArgument;
Did you try to associate the click event for that grid during page load ?
I think that is because of GridViewCommandEventArgs which commonly used for RowCommand , change it to EventArgs, so that event should be something like this:
protected void gv_Quals_RowCommand(object sender, EventArgs e)
{
ImageButton btn = (ImageButton)sender;
string cmName= btn.CommandName;
string cmArgument= btn.CommandArgument;
if ((cmName == "Remove"))
{
.....
}
}
or to get row index:
GridViewRow gvRow = (GridViewRow)(sender as Control).Parent.Parent;
int index = gvRow.RowIndex;
The first parent is the GridView Cell and the second parent of the GridView Cell is the GridView Row.

The GridView ' ' fired event RowUpdating which wasn't handled. C# code behind asp.net

There are similar questions on Stackoverflow and other websites, but I seem to miss something.
I have a GridView bound to a DataTable which comes from a database. My goal is to update the one row at the time with a button which is in the same row which calls the following Method.
protected void TestsToBeDone_RowUpdating(object sender, GridViewEditEventArgs e)
{
SqlConnection myConnection = getConnection();
myConnection.Open();
int index = Convert.ToInt32(e.NewEditIndex);
GridViewRow selectedRow = TestsToBeDone.Rows[index];
TableCell LABAVIDc = selectedRow.Cells[1];
int LABAVID = Convert.ToInt32(LABAVIDc.Text);
TableCell assistentc = selectedRow.Cells[5];
string query = "UPDATE Labaanvraag " +
"SET Status='4' "+
"WHERE LABAVID ='"+LABAVID+"'";
}
SqlCommand commandZ = new SqlCommand(query, myConnection);
commandZ.ExecuteNonQuery();
myConnection.Close();
SetPatientTestGrid(Session["PATID"], e);
}
It is being called from here:
<asp:GridView ID="TestsToBeDone" runat="server" EnableModelValidation="True" OnRowEditing="TestsToBeDone_RowUpdating">
<Columns>
<asp:ButtonField ButtonType="Button" CommandName="Update"
HeaderText="Afgenomen" ShowHeader="True" Text="Afgenomen" />
</Columns>
</asp:GridView>
At my first try I had a OnRowCommand with the GridViewCommandEventArgs at the code behind.
But it still throws the same exception, although I've read on a couple of sites that changing it to OnRowEditing and GridViewEditEventArgs would solve the problem.
Thanks in advance,
Tim A
GridView's in ASP.NET have some built in commands - Deleted, Update, etc. What's happening is that your button has a command name of Update, and the Gridview is hijacking that from you and firing a RowUpdating event instead of your RowEditing event. Change your button command name to be Edit, and use a RowEditing event.
If you are using the Row_Command event to edit, then don't use the button command name "Update" for Update and "Delete" for Delete. Instead, use Edit or UP and Del respectively.

accessing data of a GridView on button click

I am having a gridview with some columns and a template field column that contains a button and I want to call a procedure on button click, however I want to pass a value of a column to the procedure but I am getting an error, here is the action listener of the button: (column name in the gridview is team_ID)
error: Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control.
error line: int team_ID = Convert.ToInt32(Eval("team_ID"));
protected void Button1_Click(object sender, EventArgs e)
{
string connStr = ConfigurationManager.ConnectionStrings["MyDbConn"].ToString();
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand("join_team", conn);
cmd.CommandType = CommandType.StoredProcedure;
int team_ID = Convert.ToInt32(Eval("team_ID"));
string email = Session["email"].ToString();
cmd.Parameters.Add(new SqlParameter("#team_ID", team_ID));
cmd.Parameters.Add(new SqlParameter("#myemail", email));
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
First, to handle a button what was clicked in an TemplateField, you'll want to subscribe to the RowCommand method:
<asp:GridView runat="server" ID="gv" OnRowCommand="yourMethod">
You can have multiple buttons in your grid and surmise which caused the click with the CommandName property. The code below shows this, as well as how to get the row of the button that was clicked, and retrieve other controls from that row so you can get their values.
<asp:TemplateField>
<ItemTemplate>
<asp:Button CommandName="yourButtonName" runat="server" />
Code Behind
protected void yourMethod(object sender, GridViewCommandEventArgs e) {
if (e.CommandName == "yourButtonName") {
GridViewRow row = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
TextBox someTextBox = row.FindControl("tb") as TextBox;
string textValue = someTextBox.Text;
}
}

Problems submitting dynamic checkbox values

I'm working on creating a dynamic list of checklists and came to the below implementation. I have been trying for a week now to get the fnameID text values on the submit button click to send the values into the database. I do not want to use the postback oncheckedchanged.on each check because the checklist is over 1000 rows long and each postback/reload wastes too many resources. I just want to be able to use some method to be able to grab the checked values so I can insert them into the database on the submit button "Click Me!" click.
I googled and found the FindControl method but i still am not able to grab the fnameID values. I either get a undefined or it errors out on me. Any help would be greatly appreciated! Thanks!
aspx:
<div id="aGAccountabilityCheckListBox">
"Panel1" runat="server">
<asp:LinkButton ID="LinkButton1" Width="66px" runat="server" onclick="LinkButton1_Click">
Click Me!
</asp:LinkButton>
code behind:
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < 50; i++)
{
CheckBox _checkbox = new CheckBox();
_checkbox.ID = "dynamicCheckListBox" + Convert.ToString(i);
Panel1.Controls.Add(_checkbox);
Panel1.Controls.Add(" <span id='fnameID" + i + "' >test" + i + "</span>");
}
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["cnDatabase"].ToString());
SqlCommand cmd = new SqlCommand("usp_CreateUser", cn);
cmd.CommandType = CommandType.StoredProcedure;
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
Thanks!
State is restored to controls before the load event runs. If your controls don't already exist by then, they'll lose their state and you won't know they were checked. Create your checkboxes in the Init or PreInit event instead.
move the checkbox creation to the CreateChildControls page method
to retrieve checkbox state in the LinkButton1_Click handler you can use the following code
for (int i = 0; i < 50; i++)
{
string cbxId = string.Format("dynamicCheckListBox{0}", i);
CheckBox _checkbox = Panel1.FindControl(cbxId) as CheckBox;
if (_checkbox == null )
continue;
if ( _checkbox.Checked )
//do something
}
Your fnameID's are spans created as a literal control. There is no post back value you are going to get if you set it up that way. It's just arbitrary html or text from the asp.net perspective.
Why are you not using the Text property for CheckBox?

Categories