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">
Related
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.
I am working in a project where i need to list the database child items in listview2 who's parent items reside in listview1 already. here is my listview1 code;
<asp:ListView
ID="ListView1"OnSelectedIndexChanged="ListView1_SelectedIndexChanged" runat="server">
<ItemTemplate>
<a href='<%# Eval("Module_Redirect") %>'> <img src="<%#
Eval("Module_img") %>" /> </a>
</ItemTemplate>
the .cs page code is as follow(which is not working yet!)
protected void ListView1_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.ListView1.SelectedIndex == 3)
{
SqlDataAdapter da2 = new SqlDataAdapter();
da2.SelectCommand = new SqlCommand("select * from tbl_Forms where Module_ID=3 ", conn);
DataTable dt2= new DataTable();
da2.Fill(dt2);
ListView2.DataSource = dt2;
ListView2.DataBind();
}
}
My point is: how can in fetch the selected item templete of listview1 and show the relevent record in listview2?
you can try this.
using (SqlConnection con = new SqlConnection("YourConnectioString"))
{
using (SqlDataAdapter da2 = new SqlDataAdapter { SelectCommand = new SqlCommand("select * from tbl_Forms where Module_ID = #Module_ID ", con) })
{
// as your using index as the parameter,,
da2.SelectCommand.Parameters.AddWithValue("#Module_ID", ListView1.SelectedIndex);
// or if your trying to pass parameter Module_ID from ListView1 DataKey ,, you can use SelectedDataKey
//da2.SelectCommand.Parameters.AddWithValue("#Module_ID", ListView1.SelectedDataKey);
using (DataTable dt2 = new DataTable())
{
con.Open();
da2.Fill(dt2);
ListView2.DataSource = dt2;
ListView2.DataBind();
}
}
}
I am looking a way to allow my two EVALS in my CS. The 1st string works perfectly, but the other one does not
This is my aspx
<asp:ListView ID="lvMaterialsList" runat="server" ondatabound="lvMaterialsList_DataBound"
onpagepropertieschanging="lvMaterialsList_PagePropertiesChanging" OnItemCommand="lvMaterialsList_ItemCommand">
<ItemTemplate>
<tr>
<td>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("SupplierProduct")%> ' Visible="false" /></td>
<td>
<td>
<asp:Label ID="ltRefNo" runat="server" Text='<%# Eval("ReqMatID") %>' Visible="false" />
<%# Eval("SupplierProduct")%>
</td>
<td>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("SupplierProductID") %>' width="1px" Visible="false" />
</td>
<td><%# Eval("Quantity") %></td>
<td><asp:TextBox ID="txtAlloted" runat="server" type="number" Text=''
class="form-control" width="60px" min='1'/></td>
<td><asp:LinkButton ID="btnUpdate" runat="server" OnClientClick='return confirm("Withdraw materials?")' CommandName="updateused">
<i class="fa fa-refresh"></i> </asp:LinkButton>
</td>
<td><asp:Literal ID="ltUsed" runat="server" Text='<%# Eval("Used") %>'
Visible="false" />
<%# Eval("Used")%>
</td>
<td><%# Eval("Status") %></td>
<td><%# Eval("DateAdded", "{0: MMMM dd, yyyy}") %></td>
<td><%# Eval("DateModified", "{0: MMMM dd, yyyy}") %></td>
<td>
<td>
<asp:LinkButton Text="Additional" class="btn btn-primary " ID="lbtnUpdate" runat="server" CommandArgument='<%#Eval("ProjectID")+","+ Eval("ReqMatID")%>'
PostBackUrl='<%# string.Format(" AdditionalAlloc.aspx?ID={0}&MID={1}", Eval("ProjectID"), Eval("ReqMatID"))%>'></asp:LinkButton>
<asp:LinkButton Text="Add req" class="btn btn-primary " ID="lblAdd" runat="server"
PostBackUrl='<%# string.Format(" AddReq.aspx?ID={0}", Eval("ProjectID"))%>'></asp:LinkButton>
</i>
<%-- </i> --%>
<a href='DeleteMaterial.aspx?ID=<%# Eval("ReqMatID") %>'" onclick='return confirm("Delete record?")'>
<i class="fa fa-trash-o"></i>
</a>
</td>
</tr>
</ItemTemplate>
<EmptyDataTemplate>
<tr>
<td colspan="12"><h2 class="text-center">No records found.</h2></td>
</td>
</tr>
</EmptyDataTemplate>
</asp:ListView>
This is the code that I use.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class Admin_Project_AdditionalAlloc : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(Helper.GetCon());
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["ID"] != null)
{
int userID = 0;
bool validUser = int.TryParse(Request.QueryString["ID"].ToString(), out userID);
int productID = 0;
bool product = int.TryParse(Request.QueryString["MID"].ToString(), out productID);
if (validUser)
{
if (!IsPostBack)
{
GetInfo(userID);
GetMaterialsInfo(productID);
GetProjects();
GetMaterials();
}
}
else
Response.Redirect("Default.aspx");
}
else
Response.Redirect("Default.aspx");
ddlProjectName.Enabled = false;
ddlProjectName.CssClass = "form-control";
ddlMaterials.Enabled = false;
ddlMaterials.CssClass = "form-control";
Panel1.Visible = false;
}
void GetProjects()
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT ProjectID, ProjectName FROM Project";
SqlDataReader dr = cmd.ExecuteReader();
ddlProjectName.DataSource = dr;
ddlProjectName.DataTextField = "ProjectName";
ddlProjectName.DataValueField = "ProjectID";
ddlProjectName.DataBind();
con.Close();
ddlProjectName.Items.Insert(0, new ListItem("Select Project", ""));
}
void GetInfo(int ID)
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = #"SELECT ProjectID FROM Project WHERE ProjectID=#ProjectID";
cmd.Parameters.AddWithValue("#ProjectID", ID);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
ddlProjectName.SelectedValue = dr["ProjectID"].ToString();
}
con.Close();
}
else
{
con.Close();
Response.Redirect("Default.aspx");
}
}
void GetMaterialsInfo(int MID)
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = #"SELECT project.ProjectID, RequiredMaterials.ReqMatID FROM Project Inner join RequiredMaterials on RequiredMaterials.ProjectID = Project.ProjectID WHERE Project.ProjectID=#ProjectID AND RequiredMaterials.ReqMatID=#ReqMatID";
cmd.Parameters.AddWithValue("#ProjectID", ID);
cmd.Parameters.AddWithValue("#ReqMatID", MID);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
ddlMaterials.SelectedValue = dr["ReqMatID"].ToString();
}
con.Close();
}
else
{
con.Close();
//Response.Redirect("Default.aspx");
}
}
void GetMaterials()
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT project.ProjectID, ProjectName, RequiredMaterials.ReqMatID, Products.ProductName + ' (' + SupplierName +')' as SupplierProduct FROM Project Inner join RequiredMaterials on RequiredMaterials.ProjectID = Project.ProjectID INNER JOIN SupplierProducts ON RequiredMaterials.ProductID = SupplierProducts.ProductID INNER JOIN Products ON SupplierProducts.ProductID = Products.ProductID INNER JOIN Supplier ON SupplierProducts.SupplierID = Supplier.SupplierID WHERE Project.ProjectID=#ProjectID AND RequiredMaterials.ReqMatID=#ReqMatID ";
cmd.Parameters.AddWithValue("#ProjectID", ID);
cmd.Parameters.AddWithValue("#ReqMatID", ID);
SqlDataReader dr = cmd.ExecuteReader();
ddlMaterials.DataSource = dr;
ddlMaterials.DataTextField = "SupplierProduct";
ddlMaterials.DataValueField = "ReqMatID";
ddlMaterials.DataBind();
con.Close();
ddlMaterials.Items.Insert(0, new ListItem("Select Project", ""));
}
}
This is how I am using my listview
protected void lvMaterialsList_ItemCommand(object sender, ListViewCommandEventArgs e)
{
Label ltRefNo = (Label)e.Item.FindControl("ltRefNo");
Label label1 = (Label)e.Item.FindControl("Label1");
Label label2 = (Label)e.Item.FindControl("Label2");
TextBox txtAlloted = (TextBox)e.Item.FindControl("txtAlloted");
Literal ltUsed = (Literal)e.Item.FindControl("ltUsed");
bool existingSupply = IsExisting();
bool hasquantity = HasInventory(label1.Text);
int alloted = Convert.ToInt32(txtAlloted.Text);
int productid = Convert.ToInt32(label1.Text);
string Label2 = label2.Text;
var inventory = new DataTable();
using (var da = new SqlDataAdapter("SELECT * FROM Inventory", con))
{
da.Fill(inventory);
}
var products = new DataTable();
using (var da = new SqlDataAdapter("SELECT * FROM SupplierProducts", con))
{
da.Fill(products);
}
if (e.CommandName == "updateused")
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
if (alloted < 0)
{
quantityCheck.Text = "cannot input negative number as quantity";
Panel1.Visible = true;
return;
}
int finalQuantity = Convert.ToInt32(inventory.Rows[0]["Quantity"]) - alloted;
int criticalLevel = Convert.ToInt32(products.Rows[0]["CriticalLevel"]);
bool isSafe = finalQuantity >= criticalLevel;
string status = String.Empty;
if (finalQuantity <= criticalLevel && finalQuantity != 0)
{
status = "Critical";
}
else if (finalQuantity > criticalLevel)
{
status = "Available";
}
else
{
status = "Unavailable";
}
if (existingSupply && hasquantity && isSafe)
{
cmd.CommandText = "UPDATE RequiredMaterials SET Used=Used + #Used, DateModified=#DateModified WHERE ReqMatID=#ReqMatID";
cmd.Parameters.AddWithValue("#Used", alloted);
cmd.Parameters.AddWithValue("#ReqMatID", ltRefNo.Text);
cmd.Parameters.AddWithValue("#DateModified", DateTime.Now);
cmd.ExecuteNonQuery();
cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "UPDATE Inventory SET Quantity = Quantity - #Quantity, Status=#Status " +
"WHERE ProductID=#ProductID";
cmd.Parameters.AddWithValue("#Quantity", alloted);
cmd.Parameters.AddWithValue("#ProductID", productid);
cmd.Parameters.AddWithValue("#Status", status);
cmd.ExecuteNonQuery();
cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "INSERT INTO Withdraw VALUES (#ProjectID, #ProductID, #SupplierID, #Quantity,#UserID, #DateWithdrawn)";
cmd.Parameters.AddWithValue("#ProjectID", ddlProjects.SelectedValue);
cmd.Parameters.AddWithValue("#ProductID", productid);
cmd.Parameters.AddWithValue("#SupplierID", DBNull.Value );
cmd.Parameters.AddWithValue("#Quantity", alloted);
cmd.Parameters.AddWithValue("#UserID", Session["userid"].ToString());
cmd.Parameters.AddWithValue("#DateWithdrawn", DateTime.Now);
cmd.ExecuteNonQuery();
con.Close();
GetMaterialsList();
}
else if (!isSafe)
{
quantityCheck.Text = Label2 + #" Inventory count will be lower than the critical level.";
Panel1.Visible = true;
}
else
{
Panel1.Visible = true;
quantityCheck.Text = Label2 + " Cannot input inventory";
}
}
}
I keep on getting an error:
Object reference not set to an instance of an object.
I have debug the system and it show:
Conversion failed when converting the nvarchar value '__Page' to data type int.
Since you have your LinkButton on the form itself and not inside any databound control your current code will not work because Eval method can be only used with databound controls. Now, I am really not sure how you are able to get ProjectID working. You should always try to avoid complicating the mark-up code. If you have everything in your code behind file why complicate things? Simply do it in your code behind file.
MarkUp (aspx page):-
<asp:LinkButton ID="lbtnUpdate" Text="Additional" class="btn btn-primary"
runat="server"></asp:LinkButton>
In Code Behind:-
lbtnUpdate.PostBackUrl = String.Format("AdditionalAlloc.aspx?ID={0}&MID={1}",
ProjectID,ReqMatID);
I am trying to insert multiple selected values of a asp.DropdownList into multiple rows of a database. I am using Silvio Montero bootstrap select CSS to acheive multiple selection.
I am using a foreach() loop to do it but only the first selected item is getting inserted into the database. The asp.DropdownList is populated from another database.
<asp:ListBox runat="server" CssClass="selectpicker form-control" multiple data-live-search="true" ID="DropDownList1" DataTextField="username" DataValueField="username" >
</asp:ListBox>
Here is the c# code for that -
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDropDownList();
}
}
private void BindDropDownList()
{
using (SqlConnection con = new SqlConnection(CS))
using (SqlCommand cmd = new SqlCommand("SELECT DISTINCT [username], [email] FROM [Login]", con))
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DropDownList1.DataSource = ds;
DropDownList1.DataTextField = "username";
DropDownList1.DataValueField = "username";
DropDownList1.DataBind();
}
}
protected void sendbutton_Click(object sender, EventArgs e)
{
foreach (ListItem item in DropDownList1.Items)
{
if (item.Selected)
{
using (SqlConnection sqlcon = new SqlConnection(CS))
{
sqlcon.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = sqlcon;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO DB (schdlby, schdldate, schdltime, sub, event, participants ) values (#schdlby, #schdldate, #schdltime, #sub, #event, #participants)";
cmd.Parameters.AddWithValue("#schdlby", Page.User.Identity.Name.ToString());
cmd.Parameters.AddWithValue("#schdldate", cl.SelectedDate.ToShortDateString());
cmd.Parameters.AddWithValue("#sub", txtsub.Text);
cmd.Parameters.AddWithValue("#schdltime", schdltime.Text.Trim());
cmd.Parameters.AddWithValue("#event", txtevent.Text);
cmd.Parameters.AddWithValue("#parti", item.Value.ToString());
cmd.ExecuteNonQuery();
// Code to send automated SMTP mail to each dropdown selection
}
}
}
}
Response.Redirect("Second.aspx");
}
Edit: I just found that it works in asp:CheckBoxList but does not work when asp:ListBox is used
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