<asp:GridView ID="GridView1" autogenerateselectbutton="True" selectedindex="0"
autogeneratecolumns="True" allowpaging="true" runat="server" CssClass="style39"
datakeynames="Email" RowCommand="GridView1_RowCommand" ShowSelectButton="True">>
I have this select button in my grid view. I have a delete button in the page. I want to delete the selected row but how can I pass the value to the delete function so that the I can write a code to delete the selected row in the database. I want to know which row is selected how to pass the value.
My grid view has a column called email and user name. I want to pass the selected row email. Thanks
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "CommandName")
{
String Email = e.CommandArgument.ToString(); // will Return current Row primary key value
MySqlConnection connectionString = new MySqlConnection("Server=127.0.0.1;Database=surelyknown;Uid=root");
connectionString.Open();
MySqlDataAdapter adapter = new MySqlDataAdapter();
MySqlCommand command = new MySqlCommand();
command = new MySqlCommand("DELETE from tbl_group, tbl_usergroups using tbl_group inner join tbl_usergroups where tbl_group.GroupID =#Email And tbl_usergroups.tbl_group_GroupID =#Email", connectionString);
command.Parameters.Add("#Email", MySqlDbType.VarChar, 25);
command.Parameters["#Email"].Value = Email;
use RowCommand event of Gridview
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "CommandName")
{
String Email = e.CommandArgument.ToString(); // will Return current Row primary key value
//..Put deletion code here....
//.....
}
}
If you are not going to delete multiple rows at the same time on the gridview a separate delete button is not needed
You can simply place the delete button inside a template field in your gridview. That way, you won't need to select a gridview row then press the delete button on your page(2 steps)
You can then write a click event for that button & fetch the current gridview row's current index by either using DataKeys or e.CommandArgument
Let me know if you need any more help with this.
Related
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.
i am new to asp.net. I am building an admin page and i want to display employee's data in GridView by fetching it from database table. Table has 3 columns (id, name, isManager). There are three possible values for "isManager" column. These values are "yes", "no" and "null". The admin has right to decide for an employee to make him a manager by selecting "yes" or "no" from DropDownList.
This admin page has a GridView control that contains two BoundFileds (i.e. id & name) and one template field (i.e. DropDownList). I am having difficulty in displaying "isManager" column values in DropDownList. I want DropDownList to display selected value/text as "yes" if database table-row has "yes" in "isManager" column, "no" if there is "no" in table-row and display an item "Select Choice" if table-row contains a null value.
My code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string query = "select * from tblUsersTable";
DataSet ds = DataBaseConnectivity.GetData(query);
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
// RowDataBound() method
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Find the DropDownList in the Row
DropDownList ddlManager = (e.Row.FindControl("ddlManager") as DropDownList);
DataSet ds = DataBaseConnectivity.GetData
("select distinct [isManager] from tblUsersTable");
ddlManager.DataSource = ds;
ddlManager.DataTextField = "isManager";
ddlManager.DataValueField = "isManager";
ddlManager.DataBind();
ddlManager.Items.Insert(0, new ListItem("Please select","-1"));
/* After these lines of code i am not finding the right way to implement my logic
*/
Help me to figure it out.
You have to use the DataItem of the GridViewRow to access the underyling record. Then you can select the corect item via DropDownList.SelectedValue:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Find the DropDownList in the Row
DropDownList ddlManager = (e.Row.FindControl("ddlManager") as DropDownList);
DataSet ds = DataBaseConnectivity.GetData
("select distinct [isManager] from tblUsersTable");
ddlManager.DataSource = ds;
ddlManager.DataTextField = "isManager";
ddlManager.DataValueField = "isManager";
ddlManager.DataBind();
ddlManager.Items.Insert(0, new ListItem("Please select","-1"));
DataRow row = ((DataRowView)e.Row.DataItem).Row;
bool isManager= row.Field<bool>("isManager"); // use the correct type if it's not bool
ddlManager.SelectedValue = isManager.ToString();
Apart from that, i would not use such db-helper classes like DataBaseConnectivity in ASP.NET. They are just a source for nasty errors or performance issues, all the more if you use a static connection. Further informations here.
I have dynamically created GridView in my .aspx from codebehind. I inserted a sql table in that GridView. Then I added one more button filed column. Here is the code:
ButtonField bf = new ButtonField();
bf.Text = "Details";
bf.ButtonType = ButtonType.Button;
DataTable table = new DataTable();
table.Load(reader);
GridView gv = new GridView();
gv.Columns.Add(bf);
gv.DataSource = table;
gv.DataBind();
Now I want to add a MouseClickEvent on this ButtonField, but there is no property Click or MouseClick. Is there any way to do this?
For a ButtonField inside GridView you specify CommandName:
bf.CommandName = "MyCommand";
And access it like:
void gv_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "MyCommand")
{
}
}
You may find it useful: ButtonField.CommandName Property.
When it comes to gridviews that each row have an action (like edit button, or details), I personally like to do the following:
Have a hidden button right after the GridView, this button has an onclick event (let's say OnDetailsButtonClick). So this button is the one that will be making the submission.
Create a Hidden Field that will be filled when an action from a row is clicked, so that the server side code will pick up which rowId that the action was performed on
Make every button in the gridview to have OnClientClick (lets say the javascript function called goToDetails(entityId))
so the javascript function will look like:
function goToDetails(entityId){
$("#HiddenEntityId").val(entityId);
$("#Button").click()
}
from the code behind you can get the row/Entity ID from the hidden field:
private void OnDetailsButton_Click(object sender, EventArgs e){
string entityId = HiddenEntityId.Value;
//now you can do whatever you like
}
You have to use 'Gridview.RowCommand' handle to enable custom script for a button in a ButtonField..
I.e.
1) add a 'CommandName' property to your buttonfield, this example assumes the CommandName = "Delete"
2)
Protected Sub GridView1_buttonsclicked(sender As Object, e As GridViewCommandEventArgs) Handles GridView1.RowCommand
If e.CommandName = "Delete" Then
'Delete clicked with index of " + e.CommandArgument.ToString
'Your code here, using the e.commandargument as the gridview index, then select column values using that index.
End If
End Sub
The functional requirement is to fetch the list of students (3 coloums) from database (SQL Server) and display it on the web page, along with a blank field in front of each row for entering data. Next, to allow the user to enter marks scored by students in the test and update those in the database.
Now, I know this can be done using gridview by having an Update Button Field as separate coloumn. But in that case there would be an update button in front of each row and user would need to click it for each student (more than 100). This is a tedious task for user.
I want that user enters the marks for all the students and then click only 1 button, which would update all the rows.
On button click event we can use foreach loop for GridViewRows, but please help me with user interface. How to make it possible?? How to use single button click instead of 'n' clicks??
Can it be done using gridview? Or is there something else which can accomplish the task??
Thanks
place a textbox inside template field in fourth column
<asp:TemplateField HeaderText="Marks Scored">
<ItemTemplate>
<asp:TextBox runat="server" ID="txtMarksScored" />
</ItemTemplate>
</asp:TemplateField>
Then inside button click event loop through grid view rows and get the textbox to get the value entered.
protected void Submit_Click(object sender, EventArgs e)
{
foreach (GridViewRow gvr in GridView1.Rows)
{
TextBox txtMarksScored = (TextBox)gvr.FindControl("txtMarksScored");
// Hope you understand what to do next?
// txtMarksScored.Text
}
}
A complete solution for multi line editing can be found at Matt Dotsons Blog. I use it in my own application.
What you need to do at minimum, besides registering the new gridview type and exchanging your existing asp:GridView with the new type, is to tell the GridView the ID of your "SaveButton". This button will then trigger the RowUpdating/Updated events for each row that changed.
Please refer to Dotsons Blog post for details and the downloadable sourcecode.
Although very late, but may be someone my look for it. Since you did not mentioned any condition or example of code, so I assume this, below is the code:
private void UpdateAllRecord()
{
StringBuilder query = new StringBuilder();
for (int i = 0; i < GridViewName.Rows.Count; i++)
{
GridViewRow row = GridViewName.Rows[i];
using (SqlConnection con = new SqlConnection(connStr)) //use your connection string
{
con.Open();
SqlCommand cmd1 = new SqlCommand("update YourTable set ColumnName=#ColumnName where Id= " + row.Cells[0].Controls.OfType<TextBox>().FirstOrDefault().Text + " ", con);
cmd1.Parameters.AddWithValue("#ColumnName", row.Cells[5].Controls.OfType<TextBox>().FirstOrDefault().Text);
cmd1.ExecuteNonQuery();
con.Close();
}
}
}
// Now call the UpdateAllRecord() to your button click event or any other event
protected void upload_Click(object sender, EventArgs e)
{
UpdateAllRecord()
}
I made another Column in my GridView called delete. When delete is clicked, the row should be deleted or in other words, I need to get the current row's user name to delete it.
Which event should I use? (RowDeleting, Rowdeleted etc...)
How do I get the username from the current row?
Here is a great article about typical usages of DataGrid.
Enjoy.
You can use the RowDeleting event, by storing the user name in the data key collection you can access it programmatically.
<asp:GridView DataKeyNames="UserName" ID="GridView1"
runat="server" OnRowDeleting="GridView1_RowDeleting">
Then, in the code behind use the data key to delete the record.
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string userName = (string) GridView1.DataKeys[e.RowIndex].Value;
DeleteUser(userName);
}
1:-
protected void grdLst_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int i = Convert.ToInt32(grdLst.DataKeys[e.RowIndex].Value);
ob.DeleteCoverage(i);
Response.Redirect("fullcoverage.aspx");
}
2:-
GridViewRow row = (GridViewRow)grdlist.Rows[e.RowIndex];
string name = row.Cells[1].Text;
Response.Write(name.Trim());
tablename.Rows.RemoveAt(datagrid1.currentcell.rowindex);