Dropdownlist on gridview updating only first value to the database ASP.Net - asp.net

I am looking for the solution to this problem from many days, please help.
I have a grid view and have five dropdownlist on it. I have edit update and cancel edit buttons on each row.
Drop down list is updating the database, but only first value in the dropdownlist even when user select second, third or any other value from the dropdownlist.
What could possible be the reason for this. Here is my row Edit/ CancelEdit and Updating Events.
protected void gvCustomers_RowEditing(object sender, GridViewEditEventArgs e)
{
gvCustomers.EditIndex = e.NewEditIndex;
BindData();
}
protected void gvCustomers_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gvCustomers.EditIndex = -1;
BindData();
}
protected void gvCustomers_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
Label lblCustId = (Label)gvCustomers.Rows[e.RowIndex].FindControl("cust_id");
DropDownList ddlCsm = (DropDownList)gvCustomers.Rows[e.RowIndex].FindControl("CSM");
DropDownList ddlSrCsm = (DropDownList)gvCustomers.Rows[e.RowIndex].FindControl("SrCSM");
DropDownList ddlDE = (DropDownList)gvCustomers.Rows[e.RowIndex].FindControl("DE");
DropDownList ddlAE = (DropDownList)gvCustomers.Rows[e.RowIndex].FindControl("AE");
DropDownList ddlTE = (DropDownList)gvCustomers.Rows[e.RowIndex].FindControl("TE");
using (SqlConnection conn = new SqlConnection(connectionString))
{
try
{
conn.Open();
string sql = "Update SOME_TABLE SET CSM= #CSM, SrCSM= #SrCSM ,DE=#DE,AE=#AE,TE=#TE where cust_id=#cust_id";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add("#CSM", SqlDbType.VarChar).Value = ddlCsm.SelectedItem.Value;
cmd.Parameters.Add("#SrCSM", SqlDbType.VarChar).Value = ddlSrCsm.SelectedItem.Value;
cmd.Parameters.Add("#AE", SqlDbType.VarChar).Value = ddlAE.SelectedItem.Value;
cmd.Parameters.Add("#DE", SqlDbType.VarChar).Value = ddlDE.SelectedItem.Value;
cmd.Parameters.Add("#TE", SqlDbType.VarChar).Value = ddlTE.SelectedItem.Value;
cmd.ExecuteNonQuery();
}
}
catch
{ }
gvCustomers.EditIndex = -1;
BindData();
}
}
Any help would be greatly appeciated.
Thanks

just fill the dropdowns on the click of edit button and then use on rowupdating event and use ddl.SelectedValue instead of ddl.SelectedItem.Value. You will find the selected values.

Your Drop Downs are probably getting re-set in your Page_Load event. If they are, load them when the page is not in postback, like so:
if(!Page.IsPostBack) {
//set drop downs
}

Related

When I Update in Custom GridView then TextBox was return null

I'm trying to update data in GridView and when I click on Edit then data was bound and display in TextBox but when I click on Update and debug it then TextBox return null value and update with that null value
protected void grdCustomer_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
TextBox txtUserName = (TextBox)grdCustomer.Rows[e.RowIndex].FindControl("txtUserName");
command = new SqlCommand("Users_Update", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("Names", txtUserName.Text);
command.ExecuteNonQuery();
grdCustomer.EditIndex = -1;
GetData();
}

Asp.net Gridview row edit - How to remove select row event

Hi Friends wish you all Happy New Year 2017!
I am displaying records in grid and i have code to select the row and display records in text boxes as per selected row.
I have Edit Button to edit records in grid row but when i click on text box (edit mode) to enter value it is showing error because the "select row" event is still active.
Any help how to remove the select row action when edit button is clicked.
// click on the row to select and display records in text boxes
protected void gvUsrEdit_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = gvUsrEdit.SelectedRow;
Label l1 = row.FindControl("Label1") as Label;
Label l2 = row.FindControl("Label2") as Label;
i_TranInputID.Text = l1.Text;
tReason.Text = l11.Text;
gvUsrEdit.Visible = false;
}
protected void gvUsrEdit_RowEditing(object sender, GridViewEditEventArgs e)
{
gvUsrEdit.EditIndex = e.NewEditIndex;
show1();
}
public void show1()
{
string strquery = "select * from btaprs2 where vEmpID=#d1 and vQuarter=#d2 and vyear1=#d3 and tKRA=#d4 and v10='Active' ";
con.Open();
SqlCommand cmd = new SqlCommand(strquery, con);
try
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gvUsrEdit.DataSource = ds;
gvUsrEdit.DataBind();
con.Close();
}
catch (Exception ex)
{
Response.Write(ex);
Label46.Text = "Error in page please check!";
}
}
You need to change the RowIndex.
protected void gvUsrEdit_RowEditing(object sender, GridViewEditEventArgs e)
{
gvUsrEdit.EditIndex = -1;
show1();
}
I would suggest to Edit the rows this way:
You may want to use RowUpdating method like this:
protected void gvUsrEdit_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
i_TranInputID.Text = ((Label)gvUsrEdit.Rows[e.RowIndex].FindControl("Label1") ).Text;
tReason.Text = ((Label)gvUsrEdit.Rows[e.RowIndex].FindControl("Label2")).Text;
tReason.Text = l11.Text;
gvUsrEdit.EditIndex = -1;
show1();
}

delete record from gridview but not from database

I am trying to delete record from grid but not from Database.
I want to set database field ISDeleted 1 when data deleted from gridview but don't want to delete record from db.
My code delete records from both gridview and db.
Where to change in my code-
string strcon = ConfigurationManager.ConnectionStrings["Dbconnection"].ConnectionString;
SqlCommand command;
protected void Page_Load(object sender, EventArgs e)
{
tblAdd.Visible = false;
Label1.Visible = false;
//GridView1.DataBind();
if (!Page.IsPostBack)
{
fillLanguageGrid();
}
}
public void fillLanguageGrid()
{
GridView1.DataSourceID = "SqlDataSource1";
GridView1.DataBind();
}
protected void btnDelete_Click(object sender, EventArgs e)
{
foreach (GridViewRow gvrow in GridView1.Rows)
{
CheckBox chkdelete = (CheckBox)gvrow.FindControl("chk");
if (chkdelete.Checked)
{
string name= Convert.ToString(GridView1.DataKeys[gvrow.RowIndex].Values["Name"].ToString());
// command.Parameters.Add(new SqlParameter("#status", SqlDbType.VarChar, 50));
deleteRecordByName(name);
}
}
fillLanguageGrid();
}
public void deleteRecordByName(string Name)
{
SqlConnection sqlConnection = new SqlConnection(strcon);
using (SqlCommand command = new SqlCommand("[dbo].[hrm_Langauges]", sqlConnection))
{
// define this to be a stored procedure
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#status", SqlDbType.VarChar, 50));
// define the parameter and set its value
command.Parameters.Add(new SqlParameter("#Name", SqlDbType.VarChar)).Value = Name;
command.Parameters.Add(new SqlParameter("#IsDeleted", SqlDbType.Bit)).Value = 1;
command.Parameters["#status"].Value = "Delete";
//open connection, execute DELETE query, close connection
sqlConnection.Open();
command.ExecuteNonQuery();
sqlConnection.Dispose();
}
}
For that you need to add a column in your respective database table whether to show that record or not.For Ex: add column like Visible int.
Assume if
Visible =1 --> Show that record in gridview
Visible =0 --> Hide that record in gridview
By default make Visible =1 so all records are shown in gridview(write the query like Select ......Where Visible =1).when you try to delete record use update query that need to update Visible column 1 to 0.So your gridview only shows records where visible =1 .That particular deleted record is not shown in your gridview because its Visible column is 0.Try this..

I need a DropDown value that is linked to another page

I have a DropDown List where I have brought the values from my Database using code-behind.
I have added a new value after reading data from source, called ".. Add new skill".
Now when user clicks on that item I need a small page (or rather a new page) to open to add the skills that are not mentioned in the DropDownList.
if (!IsPostBack)
{
SqlConnection myConn = new SqlConnection(#"Data Source=USER-PC\SQLEXPRESS;Initial Catalog=KKSTech;Integrated Security=True");
SqlCommand myCmd = new SqlCommand(
"SELECT SkillName, SkillID FROM Skills", myConn);
myConn.Open();
SqlDataReader myReader = myCmd.ExecuteReader();
//Set up the data binding.
DropDownList1.DataSource = myReader;
DropDownList1.DataTextField = "SKillName";
DropDownList1.DataValueField = "SkillID";
DropDownList1.DataBind();
//Close the connection.
myConn.Close();
myReader.Close();
//Add the item at the first position.
DropDownList1.Items.Insert(0, "..Add New Skill");
}
This is my code-behind file.. How do I link that now?
You should use the SelectedIndexChanged event and SelectedValue property:
void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
if(String.Compare(ddl.SelectedValue,"..Add New Skill",true)==0)
Response.Redirect("Add_New_Skill.aspx");
}
Add a SelectedIndexChanged event handler to that dropdown like this
void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
if(ddl.SelectedIndex == 0)
Response.Redirect("Add_New_Skill.aspx");
}
If you want position of "...Add new skill" to be at last of the list
Use this
ddl.Items.Insert(ddl.Items.Count, "...Add New Skill");
Now to redirect to another page you should do this
void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
if(ddl.SelectedIndex == ddl.Items.Count-1)
Response.Redirect("Add_New_Skill.aspx");
}
Set AutoPostBack to true. That way when the user changes an option, it will automatically post the page to the server.
Handle this SelectedIndexChanged event, and redirect to your add page there.
Take your user to a add page.
Add the details to the database.
Bring the user back to this page.
List will be reloaded from database, and you till get your value.
No special linking is required.
This is working
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindDropdownlist()
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string getvalue = DropDownList1.SelectedItem.Value;
if (getvalue == "..Add New Skill")
{
Response.Redirect("Default.apsx");
}
}
public void bindDropdownlist()
{
SqlDataAdapter dap = new SqlDataAdapter("select coloumn1,colum2 from table", con);
DataSet ds = new DataSet();
dap.Fill(ds);
DropDownList1.DataSource = ds.Tables[0];
DropDownList1.DataTextField = "coloumn1";
DropDownList1.DataValueField = "colum2 ";
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, "..Add New Skill");
}
}
<div>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
</div>

Using DropDown_SelectedIndexChanged to bind gridview, but paging is not working

I have a DropDownList which is having few list items. Every time I select any item, based on it I am binding a gridview, hence resulting gridview depends on my selection. Some results are exceeding the pagesize hence I need to navigate on 2nd page in GridView, however the GridView is disappeating when I am selecting 2nd page.
protected void DDL_SelectedIndexChanged(object sender, EventArgs e)
{
string constr = ConfigurationSettings.AppSettings["ConnectionInfo"];
SqlConnection con = new SqlConnection(constr);
con.Open();
string str = string.Empty;
str = "SELECT * FROM Table1";
SqlDataAdapter adp = new SqlDataAdapter(str, con);
DataSet ds = new DataSet();
adp.Fill(ds, "myds");
BusinessKPIGrid.DataSource = ds;
BusinessKPIGrid.DataBind();
}
protected void OnGridViewPaging(object sender, GridViewPageEventArgs e)
{
//I know I need to bind the gridview here, but how ?
BusinessKPIGrid.PageIndex = e.NewPageIndex;
BusinessKPIGrid.DataBind();
}
I don't know how to bind the gridview in paging event, since I do not have any separate binding function.
there is a separate function for page event for grid view..create separate method for binding grid & call that method on pageindexchange event..
protected void BusinessKPIGrid_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
BusinessKPIGrid.PageIndex = e.NewPageIndex;
bindyourgrid();
}
try this
protected void DDL_SelectedIndexChanged(object sender, EventArgs e)
{
string constr = ConfigurationSettings.AppSettings["ConnectionInfo"];
SqlConnection con = new SqlConnection(constr);
con.Open();
string str = string.Empty;
str = "SELECT * FROM Table1";
SqlDataAdapter adp = new SqlDataAdapter(str, con);
DataSet ds = new DataSet();
adp.Fill(ds, "myds");
ViewState["ds"]=ds;
BusinessKPIGrid.DataSource = ds;
BusinessKPIGrid.DataBind();
}
protected void OnGridViewPaging(object sender, GridViewPageEventArgs e)
{
//I know I need to bind the gridview here, but how ?
BusinessKPIGrid.PageIndex = e.NewPageIndex;
BusinessKPIGrid.DataSource = (DataSet)ViewState["ds"];
BusinessKPIGrid.DataBind();
}
From DDL_SelectedIndexChanged if you are searching some thing then use 'PageIndexChanging' and set the page size for it
protected void gvworker_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvworker.PageIndex = e.NewPageIndex;
//result got from ddl list i.e bind your data set
}

Resources