I'm building a asp.net page in C#.
I have a GridView that when I click on it I want the content in the cell. The problem is that nothing at all happens when I click on in. What is wrong?
In my aspx-file:
<asp:GridView ID="GridView1" runat="server" Height="224px" Width="589px" IsItemClickEnabled="True" SelectionChanged="GridView1_SelectedIndexChanged" OnSelectedIndexChanged="GridView1_SelectedIndexChanged"></asp:GridView>
In my cs-file:
protected void Page_Load(object sender, EventArgs e)
{
NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;Port=5432;Database=ssys;User Id=postgres;Password=postgres;"); //Skapar connectionobjektet
conn.Open();
NpgsqlCommand command = new NpgsqlCommand("SELECT * FROM times", conn);
NpgsqlDataReader dr = command.ExecuteReader();
GridView1.DataSource = dr;
GridView1.DataBind();
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
string item = (string)(GridView1.Rows[0].Cells[0]).Text;
MessageBox.Show(item);
}
Just clicking the row in the gridview does not trigger the SelectedIndexChanged event.
From MSDN:
Occurs when a row's Select button is clicked, but after the GridView control handles the select operation.
The MSDN page tells you have to use
autogenerateselectbutton="True"
To generate a select button. This will trigger the SelectedIndexChanged.
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.
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.
i have two page ,one search.aspx and show.aspx
in search.aspx i have 2 textbox and 1 dropdownlist of location,title,experience
now when person click on search button , if person have filled location than gridview show all data of that location,if person fill both location and title than it should show data with both condition of location and title ,and if person fill all textbox and dropdownlist than it should show data with that location title and experience
now as i have gridview in another page so i am transferring all textbox and dropdown value to another page through querystring but it is not showing any data
and another what should be stored procedure for searching like this?
i have made something like
stored procedure-(it wrong but what it actually should be?)
ALTER PROCEDURE search
(
#Location nvarchar(50),
#Experience nvarchar(50),
#Title nvarchar(50)
)
AS
select * from Jobs where
Location=#Location and
Experience=#Experience and
Title=#Title
or
Location=#Location
or
Experience=#Experience
or
Title=#Title
search.aspx-
protected void imgbtnsubmit_Click(object sender, ImageClickEventArgs e)
{
Response.Redirect("show.aspx?loc,title,exp="+textloc.text+txttitle.Text+dropdownlistexperience.SelectedItem);
}
in show.aspx page ,it takes this this value in querystring and show perticular data in grdview
show.aspx-
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
dal.location = Request.QueryString["loc"];
dal.title = Request.QueryString["title"];
dal.exerience = Request.QueryString["exp"];
GridView1.DataSource = bal.search(dal);
GridView1.DataBind();
}
}
bal-
public DataTable search(portalDal dal)
{
con.Open();
cmd = new SqlCommand("search", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Location", dal.location);
cmd.Parameters.AddWithValue("#Experience", dal.experience);
cmd.Parameters.AddWithValue("#Title", dal.title);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
con.Close();
return dt;
}
errors- Procedure or function 'search' expects parameter '#Location', which was not supplied.
Your querystring isn't formatted correctly and your textloc.text should be ".Text"
protected void imgbtnsubmit_Click(object sender, ImageClickEventArgs e)
{
Response.Redirect(string.Format("show.aspx?loc={0}&title={1}&exp={1}", textloc.Text, txttitle.Text, dropdownlistexperience.SelectedItem));
}
Btw this is a great way to get a SQL Injection Attack.
In Search Page You did mistake..
protected void imgbtnsubmit_Click(object sender, ImageClickEventArgs e)
{
Response.Redirect("show.aspx?loc,title,exp="+**textloc.text**+txttitle.Text+dropdownlistexperience.SelectedItem);
}
txtloc.text ...it should be txtloc.Text
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;
}
}
<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.