binding grid view on button click in listview - c#

I have a list view with a button for each row:
<td> <asp:Button ID="Button2" runat="server" Text="select" CommandName="view" CommandArgument='<%# Eval("inquiry_id")%>' onclick="buttonClick"/></td>
On click of this button i retrieve the id of the clicked row, set the session with the same id and bind the grid view.This the code behind the button click in list view:
ListViewItem item = (sender as Button).NamingContainer as ListViewItem;
Button butDetails = (Button)item.FindControl("Button2");
Int64 inquiryID = Convert.ToInt64(butDetails.CommandArgument);
Session["session_view_id"] = inquiryID;
this.BindGrid();
return;
The session is retrieved in bindGrid function. But the problem is gridview is not displayed at first click but on second click it gets displayed but with the data of the previous id clicked.The session is set but while binding the grid it uses old session value. Where am i going wrong to bind the grid?
The code for the bindGrid() function is :
int inquiryID = Convert.ToInt32(Session["session_view_id"]);
MySqlConnection conn = null;
try
{ MySqlCommand cmd = new MySqlCommand("SELECT * FROM crm_support_inquiry inner join crm_inquiry_perticipant on crm_support_inquiry.inquiry_id=?id inner join crm_mailer_types on crm_support_inquiry.mailer_id=crm_mailer_types.mailer_id limit 4", connect);
using (MySqlDataAdapter sda = new MySqlDataAdapter())
{
cmd.Parameters.AddWithValue("?id", inquiryID);
cmd.Connection = connect;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
lblComp.Text = dt.Rows[0]["company"].ToString();
lblCname.Text = dt.Rows[0]["contact_name"].ToString();
lblEmail.Text = dt.Rows[0]["email"].ToString();
GridView1.DataSource = dt;
GridView1.DataBind();
}
}

Are you checking for IsPostBack in your Page_Load method? You need to wrap your BindGrid call in your Page_Load in an if(!IsPostBack) statement to prevent the Page_Load from initially refreshing the data on postback. This can prevent the changes you are making later on in your event handler.
protected void Page_Load(Object sender, EventArgs e)
{
if(!IsPostBack)
{
BindGrid();
}
}
This answer can provide additional info: How to update page data after event handling?

Related

How would I be able to grab the value from a drop down list control after the control has been bound with a filled data set?

How would I be able to grab the value from a dropdown list control after the control has been bound with a filled data set? Specifically, this control lives in my footer template and when the user tries to add a new row the selected item needs to be retrieved. The problem is after the dropdown list has been populated when you click on "add new" the value always returns null.
ROW COMMAND FUNCTION:
protected void userView_RowCommand(object sender, GridViewCommandEventArgs e)
{
DropDownList addUserRole = (DropDownList)userView.FooterRow.FindControl("editUserRole");
string sqlCommandText = "INSERT INTO Users(USERNAME, PHONE, EMAIL, ROLEIDFK, DEPTIDFK, ACTIVE) VALUES(#username, #phone, #email, #roleidfk, #deptidfk, #active)";
scmd.Parameters.AddWithValue("#roleidfk", addUserRole.SelectedValue.ToString()); // >>>> Returns "AddUserRole was null"
}
DROPDOWN DATABINDING:
private DataTable GetData (string query)
{
var connection = sqlConnect.connect();
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(connection.ConnectionString))
{
con.Open();
using(SqlCommand cmd = new SqlCommand(query, con))
{
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dt);
}
}
return dt;
protected void userView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
}
if ( e.Row.RowType == DataControlRowType.Footer)
{
DropDownList ddlUser = (e.Row.FindControl("ddlRoles") as DropDownList );
//query.addDataSetDdl(roles, "DESCRIPTION", "ROLEID", ddlUser);
ddlUser.DataSource = GetData("SELECT * FROM Roles");
ddlUser.DataTextField = "DESCRIPTION";
ddlUser.DataValueField = "ROLEID";
ddlUser.DataBind();
}
The problem is that the FindControl call does not use the correct id of the dropdpwnlist - at least it differs from the one that you use when databinding the dropdownlist:
DropDownList addUserRole = (DropDownList)userView.FooterRow.FindControl("editUserRole")
vs
DropDownList ddlUser = (e.Row.FindControl("ddlRoles") as DropDownList );
FindControl returns null if the control cannot be found, so if you use the correct id, the problem should be solved.

Grab SelectedValue of Dropdownlist in Gridview

Creating a list of users that haven't updated their job title in a Gridview. I want the list to have a dropdown filled with all the possible title selections and a button next to the dropdown. Then a person can come in and change the title in the dropdown hit the button and its updated and removed from the list.
I have all of this the way I want it to look but I'm trying to figure out how to pass the SelectedValue of the dropdown box in that row to the code behind OnClick. As you can see below the closest I can get is pass the row number in the CommandArgument. Any suggestions how I can get the SelectedValue of the dropdown of that specific row to the OnClick?
EDIT: Maybe I should be using OnRowCommand instead of OnClick?
Looks like this currently:
John Doe | DropdownList Button
Jane Doe | DropdownList Button
Joe Doe | DropdownList Button
Jeff Doe | DropdownList Button
ASPX
<asp:GridView runat="server" ID="TitleView" OnRowDataBound="TitleView_RowDataBound" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="Fullname" HeaderText="Fullname" />
<asp:TemplateField>
<ItemTemplate>
<div class="input-append"><asp:DropDownList CssClass="span5" ID="TitleList" runat="server">
</asp:DropDownList>
<asp:Button ID="lbnView" runat="server" Text="Update" CssClass="btn btn-primary" OnClick="btn_Clicked"
CommandArgument='<%# ((GridViewRow)Container).RowIndex %>'></asp:Button></div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Behind
public void bindTitleView()
{
using (SqlConnection conn = new SqlConnection(""))
{
SqlCommand cmd = new SqlCommand(#"SELECT U.First + ' ' + U.Last as Fullname, U.UserID, T.Name FROM Employees U LEFT JOIN Titles T ON U.Title = T.ID WHERE U.Active = '1' AND U.Title = '92' ORDER BY Fullname ASC", conn);
conn.Open();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet myDataSet = new DataSet();
adp.Fill(myDataSet);
TitleView.DataSource = myDataSet;
TitleView.DataBind();
}
}
protected void TitleView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddl = (DropDownList)e.Row.FindControl("TitleList");
using (SqlConnection conn = new SqlConnection(""))
{
SqlCommand cmd = new SqlCommand(#"SELECT ID, Name FROM Titles ORDER BY Name ASC", conn);
conn.Open();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataTable myDataSet = new DataTable();
adp.Fill(myDataSet);
ddl.DataSource = myDataSet;
ddl.DataTextField = "Name";
ddl.DataValueField = "ID";
ddl.DataBind();
}
}
}
protected void btn_Clicked(object sender, EventArgs e)
{
String rowid = ((Button)sender).CommandArgument;
}
SOLUTION: The answer I approved below worked for me once I added !IsPostBack to the Page_Load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindTitleView();
}
You can do like that:
protected void btn_Clicked(object sender, EventArgs e)
{
int line = ((GridViewRow)((Button)sender).Parent.Parent).RowIndex;
DropDownList drp = ((DropDownList)TitleView.Rows[line].FindControl("TitleList"));
//Continue the method
}
In your btn_click write the following code
protected void btn_Clicked(object sender, EventArgs e)
{
Button Sample = sender as Button;
GridViewRow row = Sample.NamingContainer as GridViewRow;
DropDownList drp = row.FindControl("TitleList") as DropDownList;
//Now use drp.SelectedValue
}
}
Let me know if this isnt what you are looking for.

Dropdown List Items Are Multiplying on clicking Gridview Select Button Each Time

Here is my Page Load Code
protected void Page_Load(object sender, EventArgs e)
{
string str = "SELECT BOOK.book_name,BOOK.price,BOOK.author,BOOK.publisher,BOOK.isbn,BOOK_APPROVAL.status,BOOK_APPROVAL.cat_id FROM BOOK INNER JOIN BOOK_APPROVAL ON BOOK.book_id = BOOK_APPROVAL.book_id";
SqlDataAdapter da = new SqlDataAdapter(str, obj.connect());
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
ds1.Clear();
DropDownList1.Items.Clear();
string str1 = "SELECT cat_id,cat_name from CATEGORY";
SqlDataAdapter da1 = new SqlDataAdapter(str1, obj.connect());
da1.Fill(ds1);
DropDownList1.DataSource = ds1;
DropDownList1.DataTextField = "cat_name";
DropDownList1.DataValueField = "cat_id";
DropDownList1.DataBind();
}
I have a dropdownlist, gridview with select button and a approve Button on the same page. When I click select button its values are displayed in series of textboxes and then i select a item from the dropdownlist. Its datavaluefield is assigned to a variable using the below code:
SqlCommand ddl = new SqlCommand("select cat_id from CATEGORY where cat_name='" + DropDownList1.SelectedItem + "' ", obj.connect());
catID = Convert.ToInt32(ddl.ExecuteScalar());
Finally when i click approve button values of all textboxes are inserted into the table where ID= dropdownlist.datavaluefield.
My problem is that when i click on the gridviews select button each time ,my dropdown list values are displayed Multiple times.
So, tried ds1.Clear() and DropDownList1.Items.Clear(); in page load, and it solved that problem, but it resets my Datavaluefield to '1'. So i can't insert into the table using selected datavaluefield.
So how can I solve this?
You just have to wrap the code in Page_Load in a !Page.IsPostBack-check:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
// code here that should be executed only at the first time
// and not on consecutive postbacks
}
}
The items are stored in ViewState by default in ASP.NET.

Deleting selected data from database C#

May I know how to delete rows from the GridView using a LinkButton? Codes I find in google are using databound GridView. I'm binding the information depending on information selected with the DropDownList. Thanks
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string username;
username = HttpContext.Current.User.Identity.Name;
if (DropDownList1.SelectedValue.Equals("Expired"))
{
SqlConnection conn4 = new SqlConnection(My connection);
SqlDataAdapter adapter;
string mySQL2;
mySQL2 =
"SELECT Title,MessageStatus From Table_Message WHERE Username ='"
+ username
+ "' AND MessageStatus = 'Expired' AND Method = 'Email'";
adapter = new SqlDataAdapter(mySQL2, conn4);
conn4.Open();
DataSet ds3 = new DataSet();
adapter.Fill(ds3);
//Execute the sql command
GridView1.DataSource = ds3;
GridView1.DataBind();
conn4.Close();
}
else if (DropDownList1.SelectedValue.Equals("Pending"))
{
SqlConnection conn3 = new SqlConnection(My connection);
SqlDataAdapter adapter1;
string mySQL;
mySQL =
"SELECT Title,MessageStatus From Table_Message WHERE Username ='"
+ username
+ "' AND MessageStatus = 'Pending' AND Method = 'Email'";
adapter1 = new SqlDataAdapter(mySQL, conn3);
conn3.Open();
DataSet ds2 = new DataSet();
adapter1.Fill(ds2);
//Execute the sql command
GridView1.DataSource = ds2;
GridView1.DataBind();
conn3.Close();
}
If you are allowing anonymous users to access the listing:
This could be an option:
Create a delete.aspx
In your query do fetch Primary Key column (Ex: Id, UId...)
In grid view make DataKeyNames = "Id"
In linkbutton`s onclick Event, redirect user to delete.aspx?Id='Your data id'
The delete.aspx could only be accessed by the authorize users. Saves accidental data loss.
In delete.aspx put a delete button, and it`s onclick event delete the record with that Unique Id.
This could be a way doing things securely.
If you are displaying listing to only authorize users, then you may write the delete code with ajax:
OnClientClick(): Write javascript functio that send request to: delete.aspx?Id='Id', delete record there.
You can take the following steps
1) Map the DataKeyNames of grid to the primary key of your table
2) Have on LinkButton as
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:ImageButton ID="imgBtnDelete" runat="server" ImageUrl="/_layouts/images/DELETE.GIF"
AlternateText="Delete" CommandName="DeleteUser" CausesValidation="false" ToolTip="Delete"/>
</ItemTemplate>
3) Bind the command argument in rowdatabound event
protected void GvwUser_RowDataBound(object sender, GridViewRowEventArgs e)
{
ImageButton imgBtnDelete;
if (e.Row.RowType == DataControlRowType.DataRow)
{
imgBtnDelete = (ImageButton)e.Row.FindControl("imgBtnDelete");
imgBtnDelete.CommandArgument = gvwUser.DataKeys[e.Row.RowIndex].Value.ToString();
}
}
4)In the code behind write the implementation as
protected void GvwUser_RowCommand(object sender, GridViewCommandEventArgs e)
{
int userId = 0;
if (e.CommandName.Equals("DeleteUser"))
{
//get the user id
userId = Convert.ToInt32(e.CommandArgument.ToString());
//GetUser will delete the user
if (DeleteUser(userId) > 0)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "Delete", "alert('User Deleted.');", true);
}
}

Form View OnPageIndexChanging Event not working

I have made AllowPaging to True in formview .It is showing the link buttons but they are not working(obviously they need a function to execute).I have OnPageIndexChangeing event like Below .Can you please tell how to jump to next page and make the pager working.I am bind the Form view using sp in Page_Load event.
Aspx code:
<asp:FormView ID="form_view_with_sp" runat="server" OnModeChanging="mode_changeing" OnPageIndexChanging="page_index_chaging" AllowPaging="true">
page_index_changing event:-
protected void page_index_chaging(object sender, FormViewPageEventArgs e)
{
}
Page_Load:-
SqlConnection con = new SqlConnection(getconnectionstring());
SqlCommand cmd = new SqlCommand();
//cmd.CommandText = "selectprocedure";
DataTable dt = new DataTable();
cmd.Connection = con;
con.Open();
SqlDataAdapter adb = new SqlDataAdapter("selectprocedure", con);
form_view_with_sp.DataSource = dt;
form_view_with_sp.DataBind();
Thanks in advance.
You will need to assign the DataSource of the FormView in the page_index_chaging event handler. Please try to use the following
protected void page_index_chaging(object sender, FormViewPageEventArgs e)
{
DataTable dt = (DataTable)ViewState["DataSource"];
form_view_with_sp.DataSource = dt;
form_view_with_sp.DataBind();
}
Remember to put the DataTable into ViewState in Page_Load event when creating the DataSource.

Categories