accessing data of a GridView on button click - c#

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;
}
}

Related

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.

How to get a specific data in gridview using c#?

I was wondering how to retrieve a specific data from gridview. My database consists of columns like id, type and name. Lets say the contents of my gridview is like this example below:
Id Type Name
1 Guitar Ibanez
2 Guitar Gibson
What i want to happen is to get the value under Name, Lets say "Ibanez". I was able to retrieve the value for Id using datakeys but I can't figure out how to get the value of Name in Gridview. I included code below to better understand what i mean.
protected void GuitarBrandsGridViewBtn_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
GridViewRow gridrow = btn.NamingContainer as GridViewRow;
int id = Convert.ToInt32(GuitarBrandsGridView.DataKeys[gridrow.RowIndex].Value.ToString());
con.Open();
cmd.CommandText = "DELETE FROM [guitarBrands] WHERE id=" + id;
cmd.Connection = con;
int a = cmd.ExecuteNonQuery();
con.Close();
if (a > 0)
{
bindgridviewguitarbrands();
}
System.IO.File.Delete(#"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\GuitarItemsIbanezDetails" + id + ".aspx");
System.IO.File.Delete(#"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\GuitarItemsIbanezDetails" + id + ".aspx.cs");
}
You can access specific columns like this
GuitarBrandsGridView.Rows[gridrow.RowIndex].Cells[1].Text;
you can use template field in the grid view instead of bound field like this :
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Eval("ColumnNameOfYourDatasourceForName") %>' />
</ItemTemplate>
</asp:TemplateField>
and then get the label and its text in code behind from following code :
protected void GuitarBrandsGridViewBtn_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
GridViewRow gridrow = btn.NamingContainer as GridViewRow;
Label lblName = gridrow.FindControl("lblName");
string name = lblName.Text;
}

Store ID from a dropdown list

I have been working on this for a while but seems I can't figure this out. So I have a dropdown list called ddStudent where the textField value is from a sql table I made called 'Student from a column called 'firstName'. Now I used the 'studentID' as the value field.
Here is where I am having the issue. I want to execute my stored procedure that takes studentID as a paramter but I don't understand how to store the actual student ID into the parameter.
Here is what I have so far-
protected void btnRegister_Click(object sender, EventArgs e)
{
int selValClass = Convert.ToInt32(ddClassNames.SelectedValue);
int selValStudent = Convert.ToInt32(ddStudents.SelectedValue);
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("procRegStudent", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#studentID", selValStudent);
cmd.Parameters.AddWithValue("#classID", selValClass);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
and here is my code for databinding-
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("SELECT studentID, firstName, lastName, ssn, address, city, state, zip FROM Student ", con);
con.Open();
ddStudents.DataSource = cmd.ExecuteReader();
ddStudents.DataTextField = "firstName";
ddStudents.DataValueField = "studentID";
ddStudents.DataBind();
}
Now my question is, is there a way I can store the actual studentID from the dropdown list when I select it? For some reason when I do this, the page reloads and selects the first student ID for a student I didn't select. I'm not exactly sure what's going on.
Thanks.
EDIT-
I wanted to make sure I clarify-
I have 3 students in my student dropdown. When I select student 3 (with student ID 3), the first student in the dropdownlist is being passed as the parameter and I can't tell why.
This issue is logical for Dropdownlist control because your dropdownlist missed to have a defaultitem to render when it comes back from the server.The soultion is very simple you should add a default list item to be the default value when the page loads
Here I made a simple example to how can we solve this issue :
in the Page.aspx:
<asp:DropDownList ID="ddStudents" runat="server" DataTextField = "firstName" DataValueField = "studentID" AppendDataBoundItems="true">
<asp:ListItem Text="===Select Student===" Value="0"></asp:ListItem>
</asp:DropDownList>
<asp:Button ID="btnRegister" runat="server" Text="Register" OnClick="btnRegister_Click" />
<asp:Label ID="lblMessage" runat="server" Text="Label"></asp:Label>
in the Page.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDropDown();
}
}
private void BindDropDown()
{
DataTable dt = new DataTable();
dt.Columns.Add("studentID", typeof(int));
dt.Columns.Add("firstName", typeof(string));
dt.Rows.Add(dt.NewRow());
dt.Rows[0]["studentID"] = 1;
dt.Rows[0]["firstName"] = "Markus";
dt.Rows.Add(dt.NewRow());
dt.Rows[1]["studentID"] = 2;
dt.Rows[1]["firstName"] = "Arthur";
ddStudents.DataSource = dt;
ddStudents.DataBind();
}
protected void btnRegister_Click(object sender, EventArgs e)
{
if (ddStudents.SelectedIndex > 0)
{
lblMessage.Text = String.Format("You selected {0} with Number : {1}", ddStudents.SelectedItem.Text,ddStudents.SelectedValue);
}
}
Hint: I marked the dropdownlist AppendDataBoundItems Property to true just to tell the dropdownlist to include the default listitem when the data binded..
I hope my code helps you solving your problem :)
Try with this
int selValStudent = int.Parse(this.ddStudents.SelectedValue);
and put your
BindDropDown();
into your postback

Nothing happens when I click on GridView

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.

Select button in a grid view

<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.

Categories