didn't update the dropdownlist changed value asp.net C# - c#

I want to take the drop down list's selected value to update another drop down list. data binding is working. but the "ddl1"'s selected value not change when selecting an item. therefore "ddl1.SelectedValue" notworkin correctly
Please check this code & help me to correct it
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
conn.Open();
string selectmap = "select [id]+' - '+[title] as title, id from map order by id;";
SqlDataAdapter comm = new SqlDataAdapter(selectmap, conn);
DataTable dt = new DataTable();
comm.Fill(dt);
conn.Close();
ddl1.DataSource = dt;
ddl1.DataTextField = "title";
ddl1.DataValueField = "id";
ddl1.DataBind();
ddl1.Items.Insert(0, new ListItem("---- Select Map ----", "0"));
Label2.Text = ddl1.SelectedIndex.ToString();
protected void ddl1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
conn.Open();
string selectmap2 = "select [id]+' - '+[title] as title, id from map where id !='"+ddl1.SelectedValue+"' order by id;";
SqlDataAdapter comm2 = new SqlDataAdapter(selectmap2, conn);
DataTable dt2 = new DataTable();
comm2.Fill(dt2);
ddl2.DataSource = dt2;
ddl2.DataTextField = "title";
ddl2.DataValueField = "id";
ddl2.DataBind();
ddl2.Items.Insert(0, new ListItem("---- Select Map ----", "0"));
}
ASPX:
<asp:DropDownList ID="ddl1" runat="server" CssClass="form-control" AutoPostBack="True" OnSelectedIndexChanged="ddl1_SelectedIndexChanged"></asp:DropDownList>

protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
Populateddl1();
}
}
private void Populateddl1()
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
conn.Open();
string selectmap = "select [id]+' - '+[title] as title, id from map order by id;";
SqlDataAdapter comm = new SqlDataAdapter(selectmap, conn);
DataTable dt = new DataTable();
comm.Fill(dt);
conn.Close();
ddl1.DataSource = dt;
ddl1.DataTextField = "title";
ddl1.DataValueField = "id";
ddl1.DataBind();
ddl1.Items.Insert(0, new ListItem("---- Select Map ----", "0"));
}
protected void ddl1_SelectedIndexChanged(object sender, EventArgs e)
{
//Write here for populating second dropdown code
}

Related

In the below code I want to add if statement for GridViewBind() where in the else case I want to say "NO DATA TO DISPLAY"

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString);
SqlDataAdapter dadapter;
DataSet dset; "SELECT Buildingsection from Building_Section";// Another Table
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
dadapter = new SqlDataAdapter(sql, con);
dset = new DataSet();
dadapter.Fill(dset);
DropDownList1.DataSource = dset.Tables[0];
DropDownList1.DataTextField = "Buildingsection ";
DropDownList1.DataValueField = "Buildingsection ";
DropDownList1.DataBind();
GridViewBind();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewBind();
}
public void GridViewBind()
{
dadapter = new SqlDataAdapter("SELECT * from SocoetyMaintan where Id=" + DropDownList1.SelectedValue + "", con);
dset = new DataSet();
dadapter.Fill(dset);
GridView1.DataSource = dset.Tables[0];
GridView1.DataBind();
You can create another text field/control with text “NO DATA TO DISPLAY”. It will be hidden by default. Show it when condition does not satisfy and hide the grid.
Otherwise clean up the gridview data and insert the text “NO DATA TO DISPLAY” in first entry.
This code worked to solve the problem for me:
if (dset.Tables[0].Rows.Count == 0)
{
Label1.Visible = true;
Label1.Text = "No Data To Display!";
}
else Label1.Visible = false;

GridView Not showing when i delete the all rows from database table

i am facing a problem do not know how to set this problem the problem is that my project working fine but when i delete all the rows from sql databse its not show grid kindly help
your response will be highly appreciated
Here is my Code Behind
public partial class Web_grid : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
protected void BindData()
{
SqlConnection conne = new SqlConnection("Data Source=192.168.0.6;Initial Catalog=TestDataBase;Persist Security Info=True;User ID=sa;Password=malick");
DataSet ds = new DataSet();
conne.Open();
string cmdstr = "SELECT * FROM OPR1 ";
SqlCommand cmd = new SqlCommand(cmdstr, conne);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(ds);
cmd.ExecuteNonQuery();
conne.Close();
GridView1.DataSource = ds;
GridView1.DataBind();
// GridView1.DataSource =null;
// GridView1.DataSource = ds;
// GridView1.DataBind();
//ds = null;
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
SqlConnection conne = new SqlConnection("Data Source=192.168.0.6;Initial Catalog=TestDataBase;Persist Security Info=True;User ID=sa;Password=malick");
conne.Open();
if (e.CommandName.Equals("ADD"))
{
Calendar txtOpenDate = (Calendar)GridView1.FooterRow.FindControl("txtOpenDate");
TextBox txtCloseDate = (TextBox)GridView1.FooterRow.FindControl("txtCloseDate");
DropDownList DropDownListoppr = (DropDownList)GridView1.FooterRow.FindControl("DropDownListoppr");
DropDownList DropDownListStages = (DropDownList)GridView1.FooterRow.FindControl("DropDownListStages");
TextBox txtAddLine = (TextBox)GridView1.FooterRow.FindControl("txtAddLine");
TextBox txtStages = (TextBox)GridView1.FooterRow.FindControl("txtStages");
TextBox txtAddOppId = (TextBox)GridView1.FooterRow.FindControl("txtAddOppId");
string cmdstr = "insert into OPR1(OpenDate,CloseDate,SlpCode,Step_Id,Line,OpprId) values(#txtOpenDate,#txtCloseDate,#SlpCode,#Step_Id,#txtAddLine,#txtAddOppId)";
SqlCommand cmd = new SqlCommand(cmdstr, conne);
cmd.Parameters.AddWithValue("#txtOpenDate", txtOpenDate.TodaysDate);
cmd.Parameters.AddWithValue("#txtCloseDate", txtCloseDate.Text);
cmd.Parameters.AddWithValue("#Step_Id", DropDownListStages.SelectedValue.ToString()); // SelectedItem.ToString());
cmd.Parameters.AddWithValue("#SlpCode", DropDownListoppr.SelectedValue.ToString()); // SelectedItem.ToString());
cmd.Parameters.AddWithValue("#txtStages", txtStages.Text);
cmd.Parameters.AddWithValue("#txtAddLine", txtAddLine.Text);
cmd.Parameters.AddWithValue("#txtAddOppId", txtAddOppId.Text);
cmd.ExecuteNonQuery();
// this.TextBox1.Text = DropDownList1.SelectedItem.ToString();
// this.TextBox3.Text = DropDownList1.SelectedValue.ToString();
BindData();
conne.Close();
}
}
protected void GridView1_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
DropDownList DropDownListoppr = (DropDownList)e.Row.FindControl("DropDownListoppr");
DropDownList DropDownListStages = (DropDownList)e.Row.FindControl("DropDownListStages");
DataTable CardCode = new DataTable();
DataTable CardCode1 = new DataTable();
SqlConnection connection = new SqlConnection("Data Source=192.168.0.6;Initial Catalog=TestDataBase;Persist Security Info=True;User ID=sa;Password=malick");
using (connection)
{
SqlCommand theCommand = new SqlCommand("select SlpCode,SlpName from OSLP ", connection);
SqlCommand theCommand1 = new SqlCommand("select Distinct StepId, Descript from OOST ", connection);
SqlDataAdapter adapter = new SqlDataAdapter(theCommand);
SqlDataAdapter adapter1 = new SqlDataAdapter(theCommand1);
adapter.Fill(CardCode);
adapter1.Fill(CardCode1);
//DropDownList7.DataSource = CardCode;
//DropDownList7.DataTextField = "SlpName";
//DropDownList7.DataValueField = "SlpCode";
//DropDownList7.DataBind();
if (CardCode.Rows.Count > 0)
{
for (int i = 0; i < CardCode.Rows.Count; i++)
{
string name3 = CardCode.Rows[i]["SlpName"].ToString();
string slpCode = CardCode.Rows[i]["SlpCode"].ToString();
DropDownListoppr.Items.Add(new ListItem(name3, slpCode));
}
}
if (CardCode1.Rows.Count > 0)
{
for (int j = 0; j < CardCode1.Rows.Count; j++)
{
string name4 = CardCode1.Rows[j]["Descript"].ToString();
string stageCode = CardCode1.Rows[j]["StepId"].ToString();
DropDownListStages.Items.Add(new ListItem(name4, stageCode));
}
}
}
}
}
No need of cmd.ExecuteNonQuery(); in BindData Method, As you are not performing any insert,delete or update operation.
try to add this property to your aspx gridview
EmptyDataText="someText"
https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.emptydatatext(v=vs.110).aspx
or you can use EmptyDataTemplate - just like TemplateField
https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.emptydatatemplate(v=vs.110).aspx

What is the way to populate a dropdownlist from a database in asp.net by using classes?

I am trying to populate a dropdownlist from sql server by using classes as shown below. The code breaks down when it comes to bind the data into the dropdown list. It gives an error on giving the dropdownlist the dataValueField and datatTextField.
HTML... a.aspx
<asp:DropDownList ID="NationalityDropDownList" runat="server" >
</asp:DropDownList>
C#... a.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
Classes.Nationality PossibleNationality = new Classes.Nationality();
if (!Page.IsPostBack)
{
DataTable dataTable = PossibleNationality.getNationality();
NationalityDropDownList.DataSource = dataTable;
NationalityDropDownList.DataValueField = "ID";
NationalityDropDownList.DataTextField = "Nationality";
NationalityDropDownList.DataBind();
}
}
Nationality.cs
public class Nationality
{
public DataTable getNationality()
{
SqlConnection conn;
SqlCommand comm;
string connectionString = ConfigurationManager.ConnectionStrings["InformationConnection"].ConnectionString;
conn = new SqlConnection(connectionString);
comm = new SqlCommand("spGetAllUsers", conn);
comm.CommandType = CommandType.StoredProcedure;
DataTable dataTable;
try
{
conn.Open();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
dataTable = new DataTable();
da.Fill(dataTable);
}
finally
{
conn.Close();
}
return dataTable;
}
}
SQL procedure....
ALTER PROCEDURE [dbo].[spGetNationalities]
AS
BEGIN
select * from Nationality;
END
This line of code in your getNationalitymethod...
comm = new SqlCommand("spGetAllUsers", conn);
...should be this instead
comm = new SqlCommand("spGetNationalities", conn);
Databinding should work if your Nationality table has columns ID and Nationality
if (!Page.IsPostBack)
{
try
{
using (SqlConnection con = new SqlConnection("Data Source = NIPOON; Initial Catalog = CustomerOrders; Integrated Security = true"))
{
SqlCommand cmd = new SqlCommand("SELECT Name FROM Customer", con);
con.Open();
dropDownList.DataSource = cmd.ExecuteReader();
dropDownList.DataTextField = "Name";
dropDownList.DataValueField = "Name";
dropDownList.DataBind();
}
}
catch (Exception Ex)
{
Console.WriteLine("Error: " + Ex.Message);
}
GetData();
}

how to fill the dropdownlist in grip grouping control using syncfusion in asp.net

I am having a grid grouping control in syncfusion asp.net with first column cell type as combobox.here I need to fill the dropdownlist in pageload.I wrote the below code:
Sqlcommand cmd = new SqlCommand("Select item_Id, item_Name from productsnrwmtrls where item_Ctgry in('R','B')", con);
sqldataadapter da = new SqlDataAdapter(cmd);
Datatable dtLocl = new DataTable();
da.Fill(dtLocl);
DropDownList ddlrwmtrl1 = (DropDownList)GridGroupingControl1.FindControl("ddlrwmtrl");
ddlrwmtrl1.DataTextField = "item_Name";
ddlrwmtrl1.DataValueField = "item_Id";
ddlrwmtrl1.DataSource = dtLocl;
ddlrwmtrl1.DataBind();
But at this line ddlrwmtrl1.DataTextField = "item_Name"; it is showing error : Object Reference is not set to an instance of an object.
You can fill the dropdownlist in Syncfusion GridGroupingControl by using Rowdatabound.
Add the dropdown as an Item Template in ASPX file:
[**aspx**]
<syncfusion:GridColumnDescriptor MappingName="City" HeaderText="City">
<ItemTemplate>
<asp:DropDownList ID="ddlCity" runat="server"></asp:DropDownList>
</ItemTemplate>
</syncfusion:GridColumnDescriptor>
RowDataBound Event
**[cs]**
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
GetData();
this.GridGroupingControl1.RowDataBound += GridGroupingControl1_RowDataBound;
}
protected void GridGroupingControl1_RowDataBound(object sender,RowDataBoundEventArgs e)
{
if (e.Element.Kind == DisplayElementKind.Record)
{
for (int i = 0; i < e.Row.Cells.Count; i++)
{
if (((GridCell)e.Row.Cells[i]).ColumnDescriptor.Name == "City")
{
myConnection = new SqlConnection(ConnectionString);
myConnection.Open();
DropDownList ddl = (DropDownList)e.Row.Cells[i].FindControl("ddlCity");
SqlCommand cmd = new SqlCommand("SELECT Distinct City FROM Employees",
myConnection);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
myConnection.Close();
ddl.DataSource = ds;
ddl.DataTextField = "City";
ddl.DataValueField = "City";
ddl.DataBind();
ddl.Items.Insert(0, new ListItem("--Select--", "0"));
}
}
}
}
You will get the grid with dropdown like below

DropDownList Value won't change

When I select any value from the DropDownList, the first one gets selected.
The code's purpose is whenever I choose a value from the DropDownList the corresponding value from the database should be displayed in the TextBox.
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("connection string");
con.Open();
DataTable Seminars = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter("SELECT SeminarName, ID FROM SeminarData", con);
adapter.Fill(Seminars);
DropDownList1.DataSource = Seminars;
DropDownList1.DataTextField = "SeminarName";
DropDownList1.DataValueField = "SeminarName";
DropDownList1.DataBind();
con.Close();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("connection string");
con.Open();
DataTable dt = new DataTable();
SqlCommand sqlCmd = new SqlCommand("SELECT SeminarNameE,TrainerName FROM SeminarData WHERE SeminarName='" + DropDownList1.SelectedItem.Value +"'", con);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
TextBox1.Text = dt.Rows[0]["SeminarNameE"].ToString();
TextBox2.Text = dt.Rows[0]["TrainerName"].ToString();
}
}
Replace your page load with this:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack) {
SqlConnection con = new SqlConnection("connection string");
con.Open();
DataTable Seminars = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter("SELECT SeminarName, ID FROM SeminarData", con);
adapter.Fill(Seminars);
DropDownList1.DataSource = Seminars;
DropDownList1.DataTextField = "SeminarName";
DropDownList1.DataValueField = "SeminarName";
DropDownList1.DataBind();
con.Close();
}
}
It needs !Page.IsPostBack, because everytime you bind, you clear any selections. In this code, it binds on every page load. Adding !Page.IsPostback will ensure it binds only the first load.

Categories

Resources