I have a textbox whose values goes into the dropdown on button click. The problem is that when I fill all the data and submit the form. And when I come second time to see that value it disappears from the dropdown. What should I do to make the value gets in the dropdown fix. Please see the code for your reference:
<tr>
<td class="td">Location/City</td>
<td>
<asp:DropDownList CssClass="txtfld-popup" ID="ddlLocation" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlLocation_SelectedIndexChanged"></asp:DropDownList>
<asp:RequiredFieldValidator CssClass="error_msg" ID="reqLocation" ControlToValidate="ddlLocation" runat="server" ErrorMessage="Please enter location" InitialValue="--Select--" SetFocusOnError="true"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
<asp:TextBox ID="txtOtherCity" runat="server" Visible="false" CssClass="txtfld-popup"></asp:TextBox>
<asp:Button ID="btnAddDropDown" runat="server" Width="63" Text="Add" CausesValidation="false" OnClick="btnAddDropDown_Click1" />
</td>
</tr>
Also, see the code behind for your reference:-
protected void ddlLocation_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlLocation.SelectedItem.Text == "Other")
{
txtOtherCity.Visible = true;
}
else
{
txtOtherCity.Visible = false;
}
}
protected void btnAddDropDown_Click1(object sender, EventArgs e)
{
string city = txtOtherCity.Text.Trim();
if (!string.IsNullOrEmpty(city))
{
ddlLocation.Items.Add(new ListItem(city, city));
}
}
You have to store the values from the textbox into the table dbo.Cities in database. Next time when you will come back to the same page then dropdown will fetch data from db.
Then on btnAddDropDown_Click1() you should insert the value of the city from the 'txtOtherCity' TextBox to the respective table, and then bind the DropDown of the city again. Something Like
protected void btnAddDropDown_Click1(object sender, EventArgs e)
{
string strconnection = System.Configuration.ConfigurationManager.AppSettings["YourConnectionString"].ToString();
string city = txtOtherCity.Text.Trim();
DataSet ds=new DataSet();
if (!string.IsNullOrEmpty(city))
{
// Your code to insert the value of the city from the 'txtOtherCity' `TextBox` to the respective table
//Edit: this is a very rudimentary code
string query = "INSERT INTO Career.Location (State) " +
"VALUES (#city) ";
// create connection and command
using(SqlConnection cn = new SqlConnection(strconnection))
using(SqlCommand cmd = new SqlCommand(query, cn))
{
// define parameters and their values
cmd.Parameters.Add("#city", SqlDbType.VarChar, 50).Value = city;
// open connection, execute INSERT, close connection
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
query = "select State from Career.Location";
using(SqlConnection cnn = new SqlConnection(strconnection))
using(SqlCommand cmdd = new SqlCommand(query, cnn))
{
SqlDataAdapter adp = new SqlDataAdapter(cmdd);
cnn.Open();
adp .Fill(ds);
cnn.Close();
}
ddlLocation.DataSource=ds;
ddlLocation.DataTextField = "State";
ddlLocation.DataValueField = "State";
ddlLocation.DataBind();
}
}
Do you have functionality of inserting the data in the DB (not only adding the new item in the drop down list). You have to insert the city in the appropriate table to be able to see it later on.
The implementation depends on your architecture, the implementation of the DAL etc.
For example - if you are using ADO.NET, you can insert the values in the table with a stored procedure:
CREATE PROCEDURE Add_City
#CityName varchar(50),
#StateID int
AS
BEGIN
INSERT INTO dbo.Cities (CityName, StateID) values (#CityName, #StateID)
END
GO
And then call it from the app. Something like that:
using (SqlConnection con = new SqlConnection("the connection string"))
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Add_City";
cmd.Parameters.Add("#CityName", SqlDbType.VarChar).Value = txtCity.Text.Trim();
cmd.Parameters.Add("#StateID", SqlDbType.Int).Value = CountryId;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
// lblMessage.Text = "City inserted successfully!";
}
catch (Exception ex)
{
throw ex; // Or log or handle somehow the exception
}
}
I got the answer for this solution, Please see the code for your reference:-
protected void BindContrydropdown()
{
//conenction path for database
//string connection = WebConfigurationManager.ConnectionStrings["myconn"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select Id,CityName From Career.Location", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
ddllocation1.DataSource = ds;
ddllocation1.DataTextField = "CityName";
ddllocation1.DataValueField = "Id";
ddllocation1.DataBind();
ddllocation1.Items.Insert(0, new ListItem("--Select--", "0"));
ddllocation1.Items.Insert(1, new ListItem("--OTHER--", "0"));
con.Close();
}
}
protected void ddllocation1_SelectedIndexChanged(object sender, EventArgs e)
{
string country = "India";
var cities = _helper.GetLocations(country, ddllocation1.SelectedValue);
cities.Insert(0, "--Select--");
cities.Insert(1, "Other");
ddlLocation.DataSource = cities;
ddlLocation.DataBind();
}
protected void btnAddDropDown_Click1(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(constring))
{
con.Open();
//BindContrydropdown();
//if (txtOtherCity.Text != "")
//{
// txtOtherCity.Text = "";
//}
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Add_CityforLocation";
cmd.Parameters.Add("#ID", SqlDbType.VarChar).Value = 0;
cmd.Parameters.Add("#CountryName", SqlDbType.VarChar).Value = "India";
cmd.Parameters.Add("#CityName", SqlDbType.VarChar).Value = txtOtherCity.Text.Trim();
cmd.Parameters.Add("#StateName", SqlDbType.VarChar).Value = ddlLocation.SelectedItem.ToString();
cmd.Connection = con;
try
{
// con.Open();
cmd.ExecuteNonQuery();
BindContrydropdown();
// lblMessage.Text = "City inserted successfully!";
}
catch (Exception ex)
{
Response.Write(ex.Message);//You Can Haave Messagebox here
}
finally
{
con.Close();
}
}
}
Also see the html of the dropdowns:-
<tr>
<td class="td">Location/State</td>
<td>
<asp:DropDownList CssClass="txtfld-popup" ID="ddllocation1" OnSelectedIndexChanged="ddllocation1_SelectedIndexChanged" runat="server" AutoPostBack="true"></asp:DropDownList>
<asp:RequiredFieldValidator CssClass="error_msg" ID="RequiredFieldValidator1" ControlToValidate="ddllocation1" runat="server" ErrorMessage="Please enter location" InitialValue="--Select--" SetFocusOnError="true"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="td">Location/City</td>
<td>
<asp:DropDownList CssClass="txtfld-popup" ID="ddlLocation" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlLocation_SelectedIndexChanged"></asp:DropDownList>
<asp:RequiredFieldValidator CssClass="error_msg" ID="reqLocation" ControlToValidate="ddlLocation" runat="server" ErrorMessage="Please enter location" InitialValue="--Select--" SetFocusOnError="true"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
<asp:TextBox ID="txtOtherCity" runat="server" Visible="false" CssClass="txtfld-popup"></asp:TextBox>
<asp:Button ID="btnAddDropDown" runat="server" Width="63" Text="Add" CausesValidation="false" OnClick="btnAddDropDown_Click1" />
</td>
</tr>
And this solved my,
Also see the Stored procedure for the same:-
Alter PROCEDURE [dbo].[Add_CityforLocation]
-- Add the parameters for the stored procedure here
#ID int,
#CountryName nvarchar(100),
#StateName nvarchar(100),
#CityName varchar(100)
AS
BEGIN
INSERT INTO Career.Location(CountryName, StateName, CityName) values (#CountryName,#StateName,#CityName)
END
GO
Related
i'm trying to store the id number of records from the list view table thru check box and other values, and I got this error after i hit the submit button. It says there is a null.
Here is the populate the table:
void GetEmployees()
{
using (SqlConnection con = new SqlConnection(Helper.GetCon()))
{
con.Open();
string query = #"SELECT EmployeeID, FirstName, LastName, Position FROM
Employees ";
using (SqlCommand cmd = new SqlCommand(query, con))
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "EmployeeID");
lvEmployees.DataSource = ds;
lvEmployees.DataBind();
con.Close();
}
}
}
Here is the submit click code:
protected void btnAddParticipants_Click(object sender, EventArgs e)
{
foreach (ListViewDataItem item in this.lvEmployees.Items)
{
string idValue = lvEmployees.DataKeys[item.DataItemIndex].Value.ToString();
if (item.ItemType == ListViewItemType.DataItem)
{
CheckBox cb = (CheckBox)item.FindControl("cbEmpPart");
if (cb.Checked)
{
using (SqlConnection con = new SqlConnection(Helper.GetCon()))
{
con.Open();
string query = #"INSERT INTO CourseParticipants VALUES (#TrainingModuleID, #EmployeeID, #Active, #DateAdded)";
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("#TrainingModuleID", txtCourseID.Text);
cmd.Parameters.AddWithValue("#EmployeeID", 1);
cmd.Parameters.AddWithValue("#Active", 1);
cmd.Parameters.AddWithValue("#DateAdded", DateTime.Now);
cmd.ExecuteNonQuery();
//con.Close();
}
}
}
}
}
}
Here is the .aspx
<asp:ListView ID="lvEmployees" runat="server" OnPagePropertiesChanging="lvEmployees_PagePropertiesChanging" OnDataBound="lvEmployees_DataBound">
<ItemTemplate>
<tr>
<td><%# Eval("FirstName")%>,<%# Eval("LastName")%></td>
<td><%# Eval("Position")%></td>
<td>
<asp:CheckBox ID="cbEmployee" runat="server" />
</td>
</tr>
</ItemTemplate>
</asp:ListView>
Start by adding the DataKeyNames to the ListView on the aspx page.
<asp:ListView ID="lvEmployees" runat="server" DataKeyNames="EmployeeID">
I'm trying to store the selected rows using asp:checkbox to the CourseParticipants table but it doesn't store the selected records to the database. There is no error shown but it refresh to the same page and shows the checked records. I'm trying to select users.
Thank you in advance!
Here is the markup:
<table class="table table-hover">
<thead style="background-color: #92d36e">
<tr>
<td><b>Employee Name</b></td>
<td><b>Position</b></td>
<td><b>Actions</b></td>
</tr>
</thead>
<tbody>
<asp:ListView ID="lvEmployees" runat="server" OnPagePropertiesChanging="lvEmployees_PagePropertiesChanging" OnDataBound="lvEmployees_DataBound">
<ItemTemplate>
<tr>
<td><%# Eval("FirstName")%>,<%# Eval("LastName")%></td>
<td><%# Eval("Position")%></td>
<td><asp:CheckBox ID="cbEmployee" runat="server" />
</a></td>
</tr>
</ItemTemplate>
</asp:ListView>
</tbody>
</table>
<asp:Button ID="btnAddParticipants" runat="server"
class="btn btn-success" OnClick="btnAddParticipants_Click"
Text="Add Participants" />
Here is the C#
void GetEmployees()
{
using (SqlConnection con = new SqlConnection(Helper.GetCon()))
{
con.Open();
string query = #"SELECT EmployeeID, FirstName, LastName, Position FROM Employees";
using (SqlCommand cmd = new SqlCommand(query, con))
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "EmployeeID");
lvEmployees.DataSource = ds;
lvEmployees.DataBind();
con.Close();
}
}
}
protected void btnAddParticipants_Click(object sender, EventArgs e)
{
foreach (ListViewDataItem item in this.lvEmployees.Items)
{
string idValue = lvEmployees.DataKeys[item.DataItemIndex].Value.ToString();
if (item.ItemType == ListViewItemType.DataItem)
{
CheckBox cb = (CheckBox)item.FindControl("cbEmployee");
if (cb.Checked)
{
using (SqlConnection con = new SqlConnection(Helper.GetCon()))
{
con.Open();
string query = #"INSERT INTO CourseParticipants VALUES (#TrainingModuleID, #EmployeeID, #Active, #DateAdded)";
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("#TrainingModuleID", txtCourseID.Text);
cmd.Parameters.AddWithValue("#EmployeeID", idValue);
cmd.Parameters.AddWithValue("#Active", 1);
cmd.Parameters.AddWithValue("#DateAdded", DateTime.Now);
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
}
}
If it's always DateTime.Now what you want to insert, you could use the getdate() function:
string query = #"INSERT INTO CourseParticipants VALUES (#TrainingModuleID, #EmployeeID, #Active, getdate())";
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("#TrainingModuleID", txtCourseID.Text);
cmd.Parameters.AddWithValue("#EmployeeID", idValue);
cmd.Parameters.AddWithValue("#Active", 1);
cmd.ExecuteNonQuery();
}
But it's a bit DB specific, so what DB are you using?
https://learn.microsoft.com/en-us/sql/t-sql/functions/getdate-transact-sql?view=sql-server-2017
I would also cast/convert txtCourseID.Text to an int (32 or 64) depending on your db scheme. Just to make sure that it's an OK value... and not string (nvarchar).
I also removed the closing of the connection, since it's in a using block.
This was working the other day, not sure what happened but it isn't now and I cant figure it out. The label will only give me one item out of around 20(give or take) distinct items. No matter what I select in my drop down list, it always gives me that same value on the label.
HTML:
<td>
<asp:DropDownList ID="ddlCompanyCode" runat="server" CssClass="Dropdown" AutoPostBack="True" OnSelectedIndexChanged="ddlCompanyCode_SelectedIndexChanged" Width="139px" DataSourceID="CompanyCodeDS" DataTextField="CompanyCode" DataValueField="CompanyCode"></asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="ddlCompanyCode" Display="Dynamic" ErrorMessage="*Please select a drop down list item." ForeColor="#CC0000" ValidationGroup="Submit"></asp:RequiredFieldValidator>
</td>
<td>
<asp:Label ID="lblSourceSyst" runat="server" CssClass="txtLabel" Text="Select Company Code" Width="137px" ></asp:Label>
</td>
<asp:SqlDataSource ID="CompanyCodeDS" runat="server" SelectCommandType="StoredProcedure" ConnectionString="<%$ ConnectionStrings:RptDatamartConnectionString %>" SelectCommand="[AXMap].[SelectCompanyCode_GLSourceCOA]">
</asp:SqlDataSource>
C#:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlCompanyCode.Items.Add(new ListItem("--Please Select--", ""));
ddlCompanyCode.AppendDataBoundItems = true;
}
}
protected void ddlCompanyCode_SelectedIndexChanged(object sender, EventArgs e)
{
String connectionString = ConfigurationManager.ConnectionStrings["RptDatamartConnectionString"].ConnectionString;
String sqlStoredProc = "RptDatamart.AXMap.SelectCompanyCode_GLSourceCOA";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.Parameters.AddWithValue("#CompanyCode", ddlCompanyCode.SelectedItem.Value);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = sqlStoredProc;
cmd.Connection = con;
try
{
con.Open();
SqlDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
{
lblSourceSyst.Text = dataReader["SourceSystem"].ToString();
}
}
catch (Exception ex)
{
lblStatus.Text = ex.Message;
}
}
And then the stored procedure im trying to use...
ALTER PROCEDURE [AXMap].[SelectCompanyCode_GLSourceCOA]
#CompanyCode varchar(10) = Null,
#SourceSystem nvarchar(255) = Null
AS
BEGIN
SET NOCOUNT OFF;
Select distinct CompanyCode, SourceSystem from [RptDatamart].[AXMap].[GLSourceCOA]
END
my sql might be terribly off, but i would think it would work.
lblSourceSyst.Text = dataReader["SourceSystem"].ToString();
Should be:
lblSourceSyst.Text += dataReader["SourceSystem"].ToString();
I have two dropdowns. First is for State and second is one for the City. When I select the state, its respective city gets populated in the next dropdown. I have one option to add more cities through textbox on button click while selecting the Other option from the city dropdownlist.
The issue is that whenever i am adding the city from the textbox, the it gets inserted into the respective state and also the dropdownlist loses its value. I tried debugging but couldn't find the exact issue.
Please see the code for your reference:
protected void btnAddDropDown_Click1(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(constring))
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Add_CityforLocation";
cmd.Parameters.Add("#ID", SqlDbType.VarChar).Value = 0;
cmd.Parameters.Add("#CountryName", SqlDbType.VarChar).Value = "India";
cmd.Parameters.Add("#CityName", SqlDbType.VarChar).Value = txtOtherCity.Text.Trim();
cmd.Parameters.Add("#StateName", SqlDbType.VarChar).Value = ddllocation1.SelectedItem.ToString();
cmd.Connection = con;
try
{
cmd.ExecuteNonQuery();
BindContrydropdown();
}
catch (Exception ex)
{
Response.Write(ex.Message);//You Can Haave Messagebox here
}
finally
{
con.Close();
}
}
}
protected void BindContrydropdown()
{
//conenction path for database
//string connection = WebConfigurationManager.ConnectionStrings["myconn"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select Id,CityName From Career.Location", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
ddllocation1.DataSource = ds;
ddllocation1.DataTextField = "CityName";
ddllocation1.DataValueField = "Id";
ddllocation1.DataBind();
ddllocation1.Items.Insert(0, new ListItem("--Select--", "0"));
ddllocation1.Items.Insert(1, new ListItem("--OTHER--", "0"));
con.Close();
}
}
Also, see the HTML for the same:-
<tr>
<td class="td">Location/State</td>
<td>
<asp:DropDownList CssClass="txtfld-popup" ID="ddllocation1" OnSelectedIndexChanged="ddllocation1_SelectedIndexChanged" runat="server" AutoPostBack="true"></asp:DropDownList>
<asp:RequiredFieldValidator CssClass="error_msg" ID="RequiredFieldValidator1" ControlToValidate="ddllocation1" runat="server" ErrorMessage="Please enter location" InitialValue="--Select--" SetFocusOnError="true"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="td">Location/City</td>
<td>
<asp:DropDownList CssClass="txtfld-popup" ID="ddlLocation" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlLocation_SelectedIndexChanged"></asp:DropDownList>
<asp:RequiredFieldValidator CssClass="error_msg" ID="reqLocation" ControlToValidate="ddlLocation" runat="server" ErrorMessage="Please enter location" InitialValue="--Select--" SetFocusOnError="true"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
<asp:TextBox ID="txtOtherCity" runat="server" Visible="false" CssClass="txtfld-popup"></asp:TextBox>
<asp:Button ID="btnAddDropDown" runat="server" Width="63" Text="Add" CausesValidation="false" OnClick="btnAddDropDown_Click1" />
</td>
</tr>
Try this
try
{
if(!IsPostBack)
{
cmd.ExecuteNonQuery();
BindContrydropdown();
}
}
i am trying to get data from the stored procedure into the dropdownlist when the event onSelectIndexChanged is fired. But after putting the break point i get to know that the event generated is not working i.e. the control doesnot even goes into that code.
<tr>
<td><asp:Label ID="Label5" runat="server" Text="Book Category"></asp:Label></td>
<td>
<asp:DropDownList ID="ddlBookCategory" runat="server" Height="20px" Width="250px" OnSelectedIndexChanged="ddlBookCategory_SelectedIndexChanged" >
</asp:DropDownList>
</td>
</tr>
<tr>
<td><asp:Label ID="Label4" runat="server" Text="Book Subject"></asp:Label></td>
<td>
<asp:DropDownList ID="ddlBookSubject" runat="server" Height="20px" Width="250px" >
</asp:DropDownList>
</td>
</tr>
and the backend cs file coding is::
protected void Page_Load(object sender, EventArgs e)
{
connectionString = ConfigurationManager.ConnectionStrings["connectionString"].ToString();
lblmsg.Visible = false;
OleDbConnection con = new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand();
try
{
con.Open();
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "ShowBookCategory";
cmd.Connection = con;
OleDbDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
ddlBookCategory.Items.Add(new ListItem(reader["CategoryName"].ToString()));
}
}
}
catch (OleDbException ex)
{
ex.Data.ToString();
}
}
protected void ddlBookCategory_SelectedIndexChanged(object sender, EventArgs e)
{
ddlBookCategory.AutoPostBack = true;
OleDbConnection con = new OleDbConnection(connectionString);
OleDbCommand cmd2 = new OleDbCommand();
MbERPLibraryBookSubjectProperty foc = new MbERPLibraryBookSubjectProperty();
try
{
con.Open();
cmd2.CommandType = System.Data.CommandType.StoredProcedure;
cmd2.CommandText = "ShowBookSubjectWithCategory";
cmd2.Connection = con;
foc.CategoryName = ddlBookCategory.Text.ToString();
cmd2.Parameters.Add(new OleDbParameter("#CategoryName", foc.CategoryName));
cmd2.Parameters["#CategoryName"].Direction = System.Data.ParameterDirection.Input;
OleDbDataReader reader2 = cmd2.ExecuteReader();
if (reader2.HasRows)
{
while (reader2.Read())
{
ddlBookSubject.Items.Add(new ListItem(reader2["SubjectName"].ToString()));
}
}
}
catch (OleDbException ex)
{
ex.Data.ToString();
}
}
And my stored Procedure is:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER Procedure [dbo].[ShowBookSubjectWithCategory](
#CategoryName varchar(50)
)
AS
BEGIN
select * from BookSubjects Where CategoryName = #CategoryName
END
Instead of declaring autoPostBack as true in your event handler, try to set it in DropDownList declaration like bellow:
<asp:DropDownList ID="ddlBookCategory" ... autopostback="true" ... >
...
</asp:DropDownList>
If you want to set ddlBookCategory.AutoPostBack = true; dynamically then set that in pageload event.
You need to add AutoPostBack =true to the control in order for the control to signal back to the server that an event has occurred. Once you do that you can set an event handler to a method in your code behind for the selected index changed event on that control.