Sounds like an easy job but havent been able to figure it out.I have an edit profile page where all the user data is pulled from database to respective textboxes,labels etc on Page_Load.The dropdownlist is binded to a table as below.My ddl is as below :
<asp:DropDownList ID="ddlGender" runat="server" Width="160px" AutoPostBack="True" OnDataBound="ddlGender_DataBound">
</asp:DropDownList>
and is binded as below :
protected void BindGenderDropDown()
{
string CS = ConfigurationManager.ConnectionStrings["SportsActiveConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from tblGenders", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
ddlGender.DataSource = ds;
ddlGender.DataTextField = "GenderName";
ddlGender.DataValueField = "GenderId";
ddlGender.DataBind();
}
ddlGender.Items.Insert(0, new ListItem("---Select---", "0"));
ddlGender.SelectedIndex = 0;
}
I am not able to set a value in the dropdownlist though.Here is what I have done :
private void ExtractData()
{
string CS = ConfigurationManager.ConnectionStrings["fgff"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from tblRegPlayers1 where UserId='PL00011'", con);
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
string path = rdr["ProfilePicPath"].ToString();
hfImagePath.Value = Path.GetFileName(path);
txtFName.Text = rdr["FirstName"].ToString();
txtLName.Text = rdr["LastName"].ToString();
txtEmailAddress.Text = rdr["EmailAdd"].ToString();
txtContactNumber.Text = rdr["MobileNo"].ToString();
txtdob.Value = rdr["DOB"].ToString();
txtStreetAddress.Text = rdr["StreetAddress"].ToString();
txtZipCode.Text = rdr["ZipCode"].ToString();
ddlGender.Items.FindByText(rdr["Gender"].ToString()).Selected = true;
}
}
But it says 'Object is not set to an instance'. So i played around a bit and tried doing it in DataBound like this :
protected void ddlGender_DataBound(object sender, EventArgs e)
{
string CS = ConfigurationManager.ConnectionStrings["SportsActiveConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from tblRegPlayers1 where UserId='PL00011'", con);
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
ddlGender.Items.FindByText(rdr["Gender"].ToString()).Selected = true;
}
}
Now it doesnt throw any error and it doesnt select the value as well.
PS : 1.I have set Autopostback true for the ddl.
2.I am aware of sqlInjection and have made changes to make it look simpler.
My final PageLoad looks like this :
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//btnReset.Visible = false;
ExtractData();
BindDisabilityDropDown();
BindGenderDropDown();
BindStateDropDown();
}
if (hfImagePath.Value == "" || hfImagePath.Value == "0")
{
imgCropped.ImageUrl = "~/ProfilePictures/DefaultProfilePicture.png";
hfImagePath.Value = "0";
}
else
{
imgCropped.ImageUrl = "~/ProfilePictures/" + hfImagePath.Value;
}
//lblRegistration.Text = Session["Button"].ToString();
}
For one, you are calling ExtractData before you have actually bound the DropDownList in the BindGenderDropDown method. This means that your dropdown will have no items when you try to look it up and set the selected item. First things first you need to move the databinding code above ExtractData.
Second, you are you trying to set the selected value in an unusual way. Instead of attempting to FindByText you should try setting SelectedValue instead.
I will assume that the contents of rdr["Gender"] in ExtractData is the GenderId you have bound to the dropdown, and not the display value in GenderName. I will also assume that GenderId is M and F and GenderName is Male and Female (although if your actual implementation varies slightly then that's ok).
Try changing:
ddlGender.Items.FindByText(rdr["Gender"].ToString()).Selected = true;
To:
ddlGender.SelectedValue = rdr["Gender"].ToString();
Also be sure to remove the code you have added for the DataBound handler, it is not necessary here.
DataSet ds = new DataSet();
da.Fill(ds);
ddlGender.DataSource = ds;
ddlGender.DataTextField = "GenderName";
ddlGender.DataValueField = "GenderId";
ddlGender.DataBind();
You are trying to set the value to a specific Column, yet you are binding it to a DataSet and not a DataTable. (A DataSet has no columns only DataTables).
Try the following assuming the DataSet has a table returned and the column names match your table structure:
string strDesiredSelection = "Male";
DataSet ds = new DataSet();
da.Fill(ds);
ddlGender.DataSource = ds.Tables[0];
ddlGender.DataTextField = "GenderName";
ddlGender.DataValueField = "GenderId";
ddlGender.DataBind();
foreach(ListItem li in ddlGender.Items){
if(li.Value.Equals(strDesiredSelection)){
ddlGender.SelectedIndex = ddlGender.Items.IndexOf(li);
}
}
Related
I have a page to edit user profile.On page load,the data loads on to the page for the given userid.The problem is that the dropdownlists have a duplicate item which is selected.as shown below :
Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//btnReset.Visible = false;
BindDisabilityDropDown();
BindGenderDropDown();
BindStateDropDown();
ExtractUserData();
}
}
protected void BindGenderDropDown()
{
string CS = ConfigurationManager.ConnectionStrings["ss"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from tblGenders", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
ddlGender.DataSource = ds;
ddlGender.DataTextField = "GenderName";
ddlGender.DataValueField = "GenderId";
ddlGender.DataBind();
}
ddlGender.Items.Insert(0, new ListItem("---Select---", "0"));
ddlGender.SelectedIndex = 0;
}
private void ExtractUserData()
{
string CS = ConfigurationManager.ConnectionStrings["ss"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from tblAllUsers where UserId='PL00012'", con);
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
string path = rdr["ProfilePicPath"].ToString();
hfImagePath.Value = Path.GetFileName(path);
lblUserId.Text = rdr["UserId"].ToString();
txtFName.Text = rdr["FirstName"].ToString();
txtLName.Text = rdr["LastName"].ToString();
txtEmailAddress.Text = rdr["EmailAdd"].ToString();
txtContactNumber.Text = rdr["MobileNo"].ToString();
txtdob.Value = rdr["DOB"].ToString();
txtStreetAddress.Text = rdr["StreetAddress"].ToString();
txtZipCode.Text = rdr["ZipCode"].ToString();
ddlGender.SelectedItem.Text = rdr["Gender"].ToString();
ddlDisabled.SelectedItem.Text = rdr["Disabled"].ToString();
ddlState.SelectedItem.Text = rdr["State"].ToString();
ddlCity.SelectedItem.Text = rdr["City"].ToString();
}
}
What i am guessing is,the dropdownlist is loaded by BindGenderDropDown() and then the SelectedItem is added once again by ExtractData().So how can i just avoid the unwanted addition?
You can do the following while selecting DropdownList SelectedItem in ExtractUserData() method:
ddlGender.SelectedIndex = ddlGender.Items.IndexOf(ddlGender.Items.FindByText(rdr["Gender"].ToString()));
Your code ddlGender.SelectedItem.Text = rdr["Gender"].ToString(); is displaying ---Select--- with rdr["Gender"].ToString(). This code doesn't change the Items but only chooses the item.
it may help you.
if (ddlGender.Items.Contains(ddlGender.Items.FindByText(rdr["Gender"].ToString())))
{
ddlGender.Items.FindByText(rdr["Gender"].ToString()).Selected = true;
}
In your case, ddlGender.SelectedItem.Text = rdr["Gender"].ToString(); is changing text of selected index and so it is changing --Select-- to Your Selected Value.
and for selection of Item in Dropdown, I'd suggest to use below code.
ddlGender.SelectedValue = rdr["GenderId"].ToString();
Here's my code:
protected void Page_Load(object sender, EventArgs e)
{
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
connection db_obj1 = new connection();
SqlConnection sql_obj = db_obj1.Connect();
if (this.DropDownList1.SelectedIndex >= 0)
{
string brand = DropDownList1.Items[DropDownList1.SelectedIndex].ToString();
string query = "Select Product,Model, NetPrice, Cost, Profit from products where Brand='" + brand + "'";
// SqlDataReader query_read = query.ExecuteReader();
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommand command = new SqlCommand(query, sql_obj);
// cmd.Parameters.AddWithValue("#tab",);
DataTable table = new DataTable();
adapter.SelectCommand = command;
adapter.Fill(table);
// Response.Write(dt.Rows.Count.ToString());
GridView grd = new GridView();
grd.FindControl("GridView1");
grd.DataSource = table;
grd.DataBind();
}
}
The problem is that when I run the code, I only see the drop down list and no GridView even when I select dofferent options. I tried debugging and it seems that the table DOES get filled and the only problem that I think is in the line 'grd.FindControl("GridView1").Is this the proper way to give a gridview a data source?
According to me you should not use like
string brand = DropDownList1.Items[DropDownList1.SelectedIndex].ToString();
on behalf that try as below
string brand = DropDownList1.SelectedItem.Text;
after that fire a query.
i hope it will halpful.
After Edit now use this code
string query = "Select Product,Model, NetPrice, Cost, Profit from products where Brand='" + brand + "'";
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommand command = new SqlCommand(query, sql_obj);
// cmd.Parameters.AddWithValue("#tab",);
DataSet ds = new DataSet();
DataTable table;
adapter.SelectCommand = command;
adapter.Fill(ds, "ABC");
table = ds.Tables["ABC"];
// Response.Write(dt.Rows.Count.ToString());
GridView grd = new GridView();
grd.FindControl("GridView1");
grd.DataSource = table;
grd.DataBind();
Explanation
adapter.Fill(ds, "ABC");
here ABC is a temp name of table you can take anything.
table = ds.Tables["ABC"];
and write here same table name as you have taken a temp table name.
now try it.
I have a DropDownList populated from a Database.
When I select an item in the DropDownList, I want to call a procedure and pass the value of the DropDownList to the calling procedure to query a database to populate a couple of Text Boxes.
How to do this?
Code for procedure:
protected void PopulateTextBoxes()
{
SqlDataReader MyReader;
SqlConnection Conn;
SqlParameter TourIdParam;
string strConnection = ConfigurationManager.ConnectionStrings["ChinatowndbConnString"].ConnectionString;
Conn = new SqlConnection(strConnection);
SqlCommand MyCommand = new SqlCommand();
MyCommand.CommandText = "SELECT TourId, TName, TDetails FROM Chinatowndb.dbo.Tour Where TourId = #TourIdp";
MyCommand.CommandType = CommandType.Text;
MyCommand.Connection = Conn;
TourIdParam = new SqlParameter();
TourIdParam.ParameterName = "#TourIdp";
TourIdParam.SqlDbType = SqlDbType.Int;
TourIdParam.Direction = ParameterDirection.Input;
TourIdParam.Value = ddlTour.SelectedItem.Value;
MyCommand.Parameters.Add(TourIdParam);
MyCommand.Connection.Open();
MyReader = MyCommand.ExecuteReader(CommandBehavior.CloseConnection);
while (MyReader.Read())
{
tbTourName.Text = (string)MyReader["TName"];
tbTourDetails.Text = (string)MyReader["TDetails"];
lblTourId.Text = Convert.ToString(MyReader["TourId"]);
}
}
Code to populate DropDownBox:
private void PopulateTour()
{
DataTable dtTour = new DataTable();
string strConnection = ConfigurationManager.ConnectionStrings["ChinatowndbConnString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnection))
{
try
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT TourId, TName FROM Chinatowndb.dbo.Tour", con);
adapter.Fill(dtTour);
ddlTour.DataSource = dtTour;
ddlTour.DataValueField = "TourId";
ddlTour.DataTextField = "TName";
ddlTour.DataBind();
}
catch (Exception ex)
{
// Handle the error
}
}
// Add the initial item
ddlTour.Items.Insert(0, new ListItem("<Select Tour>", "0"));
}
You need to add the event handler for the selection change in your HTML
<asp:DropDownList id="ddlTour"
AutoPostBack="True"
OnSelectedIndexChanged="ddlTour_SelectedIndexChanged"
runat="server">
and process the event in your code behind
void ddlTour_SelectedIndexChanged(Object sender, EventArgs e)
{
// Call the method that gets the current item from the dropdown and fills the textboxes
PopulateTextBoxes();
}
i test my query in sql server and it's working 100%
but in my page not work !!
this my query
UPDATE Employee SET
Name='jojo',
Age=19,
GenderID=2,
CountryID=5,
Mobile=0917021092
WHERE EmployeeID=10
this my code
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string s = GridView1.DataKeys[e.RowIndex].Value.ToString();
Label id = (Label)GridView1.Rows[e.RowIndex].FindControl("lblEditID");
Label EmployeeID = (Label)GridView1.Rows[e.RowIndex].FindControl("lblEmployeeID");
TextBox name = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEditName");
TextBox age = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEditAge");
DropDownList gender = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("DropGender");
DropDownList country = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("DropCountry");
TextBox mobile = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEditMobile");
string stringconnectiong = ConfigurationManager.ConnectionStrings["Employee_TestConnectionString"].ConnectionString;
string sql = "update Employee set Name=#Name, Age=#Age,GenderID=#GenderID , CountryID=#CountryID , Mobile=#Mobile where EmployeeID=#EmployeeID AND ID=#ID";
SqlConnection con = new SqlConnection(stringconnectiong);
try
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Parameters.AddWithValue("#EmployeeID", EmployeeID.Text);
cmd.Parameters.AddWithValue("#ID", id.Text);
cmd.Parameters.AddWithValue("#Name", name.Text);
cmd.Parameters.AddWithValue("#Age", age.Text);
cmd.Parameters.AddWithValue("#GenderID", gender.SelectedValue);
cmd.Parameters.AddWithValue("#CountryID", country.SelectedValue);
cmd.Parameters.AddWithValue("#Mobile", mobile.Text);
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
cmd.Connection = con;
cmd.ExecuteNonQuery();
SqlDataAdapter dr = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
dr.Fill(ds);
GridView1.DataSource = ds;
GridView1.EditIndex = -1;
BindGridview();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Error Updating ";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
con.Close();
con.Dispose();
BindGridview();
}
}
Since your datasource is a dataset, you need to specify which data table within the dataset you are using via the DataMember propery. Or just use a data table as your datasource.
Replace the dataset lines with the following:
DataTable dt = new DataTable();
dr.Fill(dt);
GridView1.DataSource = dt;
In addition, use the GridView1_RowUpdated event. The GridView1_RowUpdating event is fired before the table is updated, therefore your parameter values have not been updated yet.
In my asp project I need to write all Items form the list box into database table using TVP. I have listbox, stored procedure (passing TVP - Table Valued Parameters). The main problem is that passing DataTable is NULL, but the Session isn't. I'll send you my code form aspx.cs file (only one block, if you'll nedd more, let me know).
protected void ASPxButton1_Click(object sender, EventArgs e)
{
//DataTable dts = Session["SelectedOptions"] as DataTable;
DataTable _dt;
//_dt = new DataTable("Items");
_dt = Session["SelectedOptions"] as DataTable;
_dt.Columns.Add("Id", typeof(int));
_dt.Columns.Add("Name", typeof(string));
foreach (ListEditItem item in lbSelectedOptions.Items)
{
DataRow dr = _dt.NewRow();
dr["Id"] = item.Value;
dr["Name"] = item.Text;
}
SqlConnection con;
string conStr = ConfigurationManager.ConnectionStrings["TestConnectionString2"].ConnectionString;
con = new SqlConnection(conStr);
con.Open();
using (con)
{
SqlCommand sqlCmd = new SqlCommand("TestTVP", con);
sqlCmd.CommandType = CommandType.StoredProcedure;
SqlParameter tvpParam = sqlCmd.Parameters.AddWithValue("#testtvp", _dt);
tvpParam.SqlDbType = SqlDbType.Structured;
sqlCmd.ExecuteNonQuery();
}
con.Close();
}
EDIT
Debugging Screenshot
You are not adding the new rows to the DataTable. You need something like this:
foreach (ListEditItem item in lbSelectedOptions.Items)
{
DataRow dr = _dt.NewRow();
dr["Id"] = item.Value;
dr["Name"] = item.Text;
_dt.Rows.Add(dr);
}
A secondary concern is where are you initialising Session["SelectedOptions"]? It appears that every time ASPxButton1 is clicked the code will try and add Id and Name columns to it, even if it already contains those two columns. It would seem more logical to do something like:
_dt = Session["SelectedOptions"] as DataTable;
if (_dt == null)
{
_dt = new DataTable("Items");
_dt.Columns.Add("Id", typeof(int));
_dt.Columns.Add("Name", typeof(string));
Session.Add("SelectedOptions", _dt);
}