ASP.NET DropdownList Always insert the first item - asp.net

I have dropdownlist on my website. When I select the any item to insert the database but it does not insert selected item always insert the first item inside the dropdown list. Please Help How can I solve that problem?
Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetCategory();
}
}
void GetCategory()
{
dlCategory.DataSource = Data.GetDataTable("SELECT * FROM tblCategory");
dlCategory.DataTextField = "CategoryName";
dlCategory.DataValueField = "ID";
dlCategory.DataBind();
dlCategory.Items.Insert(0, new ListItem("--Select--", "0"));
dlCategory.SelectedIndex = dlCategory.Items.IndexOf(dlCategory.Items.FindByText("--Select--"));
}
SqlConnection baglanti = Data.baglan();
SqlCommand tr = new SqlCommand("Insert tblProduct (CategoryID) values(#CategoryID)", baglanti);
tr.Parameters.AddWithValue("#CategoryID", dlCategory.SelectedValue);
tr.ExecuteNonQuery();

Your question is a bit blurry regarding the code, so correct me if I misunderstood, but I presume you want to do the following in WebForms:
Simply show all available categories that can be assigned to a
product
When the user selects the category and hits submit, it will be inserted to the DB assegnied to it
It is not quite elegant, but I would put something like this:
private SqlConnection _sqlConnection = new SqlConnection();
protected void Page_Load(object sender, EventArgs e)
{
_sqlConnection.ConnectionString = #".." //Assign whatever your ConnectionString is in Data.baglan();
_sqlConnection.Open();
if (!IsPostBack)
{
GetCategory();
}
else
{
//Define your insert something like this, and I would put this into the submit Button_Click event:
if (!String.IsNullOrEmpty(dlCategory.SelectedValue) && dlCategory.SelectedValue != "0")
{
SqlCommand tr = new SqlCommand("Insert tblProduct (CategoryID) values (#CategoryID)", _sqlConnection);
tr.Parameters.AddWithValue("#CategoryID", dlCategory.SelectedValue);
tr.ExecuteNonQuery();
}
else
{
//TODO: Handle wrong selection, eg display an error message..
}
}
}
void GetCategory()
{
dlCategory.DataSource = new SqlCommand("SELECT * FROM tblCategory", _sqlConnection).ExecuteReader();
dlCategory.DataTextField = "CategoryName";
dlCategory.DataValueField = "ID";
dlCategory.DataBind();
dlCategory.Items.Insert(0, new ListItem("--Select--", "0"));
dlCategory.SelectedIndex = dlCategory.Items.IndexOf(dlCategory.Items.FindByText("--Select--"));
}

Related

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

how to map a checkbox to update the database after submit.

I need to use a the session dataTable email value for the #email and the base from the dropdownlist.
protected void Page_Load(object sender, EventArgs e)
{
DropDownList1.DataSource = (DataTable)Session["dt"];
DropDownList1.DataValueField = "base";
DropDownList1.DataTextField = "base";
DropDownList1.DataBind();
}
string str;
protected void Submit_Click(object sender, EventArgs e)
{
if (CheckBox9.Checked == true)
{
str = str + CheckBox9.Text + "x";
}
}
SqlConnection con = new SqlConnection(...);
String sql = "UPDATE INQUIRY2 set Question1 = #str WHERE email = #email AND Base = #base;";
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#email", Session.dt.email);
cmd.Parameters.AddWithValue("#str", str);
cmd.Parameters.AddWithValue("#base", DropDownList1.base);
}
}
Your syntax for reading the value out of Session is wrong, you cannot use Session.dt.email.
You need to read the DataTable out of Session and cast it to a DataTable, like this:
DataTable theDataTable = null;
// Verify that dt is actually in session before trying to get it
if(Session["dt"] != null)
{
theDataTable = Session["dt"] as DataTable;
}
string email;
// Verify that the data table is not null
if(theDataTable != null)
{
email = dataTable.Rows[0]["Email"].ToString();
}
Now you can use the email string value in your SQL command parameters, like this:
cmd.Parameters.AddWithValue("#email", email);
UPDATE:
You will want to wrap your drop down list binding in Page_Load with a check for IsPostBack, because as your code is posted it will bind the drop down list every time the page loads, not just the first time, thus destroying whatever selection the user made.
Instead do this:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
DropDownList1.DataSource = (DataTable)Session["dt"];
DropDownList1.DataValueField = "base";
DropDownList1.DataTextField = "base";
DropDownList1.DataBind();
}
}
Now your base value in your database parameter logic should be the value the user selected.

How to get modified value of TextBox

This is PageLoad code
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//DropDownList Binding through bussiness logic
Bussiness_logic.DropDownList_Bind(DDL_U, "SHORT_DESC", "UNIT_CODE", "UNIT_SOURCE");
Bussiness_logic.DropDownList_Bind(DDL_Branch, "TYPE_DESC", "TYPE_CODE", "BRANCH_SOURCE");
}
if (Request.QueryString["File"] != null)
{
string fileNo = Request.QueryString["File"].ToString();
Bussiness_logic.OpenConnection();
SqlCommand com = new SqlCommand("LINK_DATA", Bussiness_logic.con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#FILE", fileNo);
SqlDataReader dtr = com.ExecuteReader();
if (dtr.HasRows)
{
dtr.Read();
{
TxtFile.Text = dtr["FILE_NO"].ToString();
DDL_Branch.SelectedValue = dtr["TYPE_DESC"].ToString();
TxtSub.Text = dtr["SUBJECT"].ToString();
DDL_U.SelectedValue = dtr["SHORT_DESC"].ToString();
}
}
Bussiness_logic.CloseConnection();
Label1.Text = "";
}
}
I have get value of QueryString from another page and file my fields according to File variable fetching data from database corresponding to File data .Fields(Two Textbox and two DropDwnList) are filling correctly but when i modify data in textbox or DDL and Click on Update button then it is not updating data .
Update Button code
protected void BtnUpdate_Click(object sender, EventArgs e)
{
Bussiness_logic.OpenConnection();
SqlCommand com = new SqlCommand("UPDATE_DATA",Bussiness_logic.con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#FILE_NO", TxtFile.Text);
com.Parameters.AddWithValue("#SUB",TxtSub.Text);
com.Parameters.AddWithValue("#UNIT",DDL_U.SelectedValue);
com.Parameters.AddWithValue("#BRANCH",DDL_Branch.SelectedValue);
com.ExecuteNonQuery();
Label1.Text = "Action perfomed successfully !!!";
Bussiness_logic.CloseConnection();
Bussiness_logic.Empty_Control(TxtFile, TxtSub, DDL_U, DDL_Branch);
//GridView1.Visible = false;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//DropDownList Binding through bussiness logic
Bussiness_logic.DropDownList_Bind(DDL_U, "SHORT_DESC", "UNIT_CODE", "UNIT_SOURCE");
Bussiness_logic.DropDownList_Bind(DDL_Branch, "TYPE_DESC", "TYPE_CODE", "BRANCH_SOURCE");
if (Request.QueryString["File"] != null)
{
string fileNo = Request.QueryString["File"].ToString();
Bussiness_logic.OpenConnection();
SqlCommand com = new SqlCommand("LINK_DATA", Bussiness_logic.con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#FILE", fileNo);
SqlDataReader dtr = com.ExecuteReader();
if (dtr.HasRows)
{
dtr.Read();
{
TxtFile.Text = dtr["FILE_NO"].ToString();
DDL_Branch.SelectedValue = dtr["TYPE_DESC"].ToString();
TxtSub.Text = dtr["SUBJECT"].ToString();
DDL_U.SelectedValue = dtr["SHORT_DESC"].ToString();
}
}
Bussiness_logic.CloseConnection();
Label1.Text = "";
}
}
}
Put Your second if also in first if.Because when you click update button than your page load event fire first.Means your textbox value again set from textbox.So putting your second if inside first if stop setting the textbox value from database on postbask,

remove previously stored value of a checkbox in a session when user unchecks this checkbox

I try to dynamically create checkboxes - all of them with assigned checkedChanged event.
In the event handler i test if the checkbox is checked and if so I sore the value attribute in a session.
But here occurs a big problem for me.
For example a client decides to check one checkboxes and it's value attribute is added to the session, but then he suddenly decides that he doesn't want that checbox to be checked and he unchecks it - it's ok, but this value will stay stored in the session and I don't eant that.
So is there any way to delete this value when the user unchecks the checkbox
protected void btnProba_Click(objectore sender, EventArgs e)
{
lblProba.Text = ((String)Session["chk"]);
// lblProba.Text = pr.ToString();
}
protected void checkChanged(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
if (chk.Checked)
{
//lblProba.Text += chk.Text;
//myche.Add(chk.Text);
Session["chk"] += chk.InputAttributes["value"];
}
}
protected void ddlNumberTourists_SelectedIndexChanged(object sender, EventArgs e)
{
chkddlchange = true;
int numTourists = Convert.ToInt32(ddlNumberTourists.SelectedItem.Text);
for (int i = 0; i < numTourists; i++)
{
string connectionString = "Server=localhost\\SQLEXPRESS;Database=excursion;Trusted_Connection=true";
string query =
"SELECT Extra_Charge_ID, Excursion_ID, Amout, Extra_Charge_Description FROM EXTRA_CHARGES WHERE Excursion_ID=" + mynewstring;
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(query, conn);
try
{
conn.Open();
SqlDataReader rd= cmd.ExecuteReader();
int s = 0;
while (rd.Read())
{
CheckBox mycheckbox = new CheckBox();
mycheckbox.ID = "chkblextracharge" + i.ToString() + s.ToString();
mycheckbox.Text = rd["Extra_Charge_Description"].ToString();
mycheckbox.InputAttributes.Add("value", rd["Extra_Charge_ID"].ToString());
mycheckbox.AutoPostBack = true;
mycheckbox.CheckedChanged += new EventHandler(checkChanged);
Page.FindControl("form1").Controls.Add(mycheckbox);
}
}//End of try
catch (Exception ex)
{ }
}//end of for
}
}
}
It seems like you store checkboxes values as a concatenated string in Session["chk"]. It makes removing anything from there pretty hard. I guess it might be better to store a list of strings in Session["chk"], so you would be able to easy add/remove entries from there...

How to make updatable GridView in ItemTemplate

I want to show Employee details in GridView. My client wants that he should be able to update the record without clicking on Edit button to update. Hence I kept everything in the ItemTemplate field of the GridView.
My Database tables are:
Emp(EmpNo, EName, Sal, DeptNo)
Dept(DeptNo, DeptName, Location)
Hence, I have written one sp to get data: EmpNo, EName, Sal, DeptName
Here, I want to show DeptName field in DropDownList. Here only I am facing the problem. DropDownList is not filling with proper DeptName value, but the first field.
My code-behind is like below:
public partial class GvwEmployee : System.Web.UI.Page
{
SqlConnection objConn = new SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["STERIAConnectionString"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GridView1.DataSource = EmployeeList;
GridView1.DataBind();
}
}
private List<Employee> EmployeeList
{
get{
List<Employee> employeeList = new List<Employee>();
SqlCommand objCmd = new SqlCommand("usp_GetEmpDetails", objConn);
objCmd.CommandType = CommandType.StoredProcedure;
objConn.Open();
SqlDataReader objDR = objCmd.ExecuteReader();
while (objDR.Read())
{
Employee employee = new Employee();
employee.EmpNo = Convert.ToInt32(objDR["EmpNo"]);
employee.EName = Convert.ToString(objDR["EName"]);
employee.Salary = Convert.ToDouble(objDR["Salary"]);
employee.DeptNo = Convert.ToInt32(objDR["DeptNo"]);
employee.DeptName = Convert.ToString(objDR["DeptName"]);
employeeList.Add(employee);
}
objDR.Close();
objConn.Close();
return employeeList;
}
}
private List<Department> DeptList
{
get
{
List<Department> deptList = new List<Department>();
SqlCommand objCmd = new SqlCommand("usp_GetDeptDetails", objConn);
objCmd.CommandType = CommandType.StoredProcedure;
objConn.Open();
SqlDataReader objDR = objCmd.ExecuteReader();
while (objDR.Read())
{
Department dept = new Department();
dept.DeptNo = Convert.ToInt32(objDR["DEPTNO"]);
dept.DName = Convert.ToString(objDR["DNAME"]);
dept.Location = Convert.ToString(objDR["Location"]);
deptList.Add(dept);
}
objDR.Close();
objConn.Close();
return deptList;
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddlDeptName = e.Row.FindControl("ddlDeptName") as DropDownList;
if (ddlDeptName != null)
{
ddlDeptName.DataSource = DeptList;
ddlDeptName.DataBind();
ddlDeptName.SelectedValue = GridView1.DataKeys[e.Row.RowIndex].Value.ToString();
}
}
if (e.Row.RowType == DataControlRowType.Footer)
{
}
}
}
Can anyone please tell where is the problem, why DeptName DropDownList is not filling with its proper values?
Try this way
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var index = Convert.ToInt32(e.RowIndex.ToString());
GridViewRow row = GridView1.Rows[index];
var ddlDeptName = row.FindControl("ddlDeptName") as ddlDeptName;
if (ddlDeptName != null)
{
ddlDeptName.DataSource = DeptList;
ddlDeptName.DataTextField = "DName";
ddlDeptName.DataValueField = "DeptNo";
ddlDeptName.DataBind();
var item = new ListItem("Select Department", "");
ddlDeptName.Items.Insert(0, item);
}
}
}
I got the solution like below:
In the GridView1_RowDataBound event method, I have written the following line of code to map DropDownList with the Data got from Backend.
//ddlDeptName.SelectedValue = GridView1.DataKeys[e.Row.RowIndex].Value.ToString();
Now, I have replaced the above line with the following line of code, and hence the problem was solved:
ddlDeptName.SelectedValue = ((Employee)e.Row.DataItem).DeptNo.ToString();
and this has solved my problem.

Resources