You need to select the data order by CityId in descending order. So that you your last inserted item will be the first element in the dropdownlist.
Page1
HTML
<asp:DropDownList ID="ddlCities" runat="server">
</asp:DropDownList>
<asp:HyperLink Text="Redirect to next page" NavigateUrl="~/Default2.aspx" runat="server" />
Namepaces
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.PopulateCities();
}
}
private void PopulateCities()
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection conn = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Cities ORDER BY CityId DESC ", conn))
{
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
DataSet ds = new DataSet();
da.Fill(ds);
ddlCities.DataValueField = "CityId";
ddlCities.DataTextField = "CityName";
ddlCities.DataSource = ds;
ddlCities.DataBind();
}
}
}
}
Second Page
HTML
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
Enter City
</td>
<td>
<asp:TextBox ID="txtCityName" runat="server" />
</td>
</tr>
<tr>
<td colspan="2">
<asp:Button runat="server" Text="Save" OnClick="Save" />
</td>
</tr>
</table>
<asp:HyperLink ID="HyperLink1" Text="Redirect to previous page" NavigateUrl="~/Default.aspx" runat="server" />
C#
protected void Save(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
string sqlStatment = "INSERT INTO Cities VALUES(@CityName)";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(sqlStatment, con))
{
cmd.Parameters.AddWithValue("@CityName", this.txtCityName.Text.Trim());
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}