I've implemented a drop down list in my webpage and bind it to a data source that I created But no matter what I chose in the page, the dropdownlist.selectedItem always get me the first element and SelectedIndex is always 0. I've contracted my code with other examples and could not find out why.
here is the code of data source creation and binding:
public void bindLanguage() {
DropDownList1.DataSource = CreateDataSource();
DropDownList1.DataTextField = "language";
DropDownList1.DataValueField = "value";
DropDownList1.DataBind();
}
public ICollection CreateDataSource()
{
string[] allLan = System.IO.File.ReadAllLines(MyGlobal.LanFile);
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add(new DataColumn("language", typeof(string)));
dt.Columns.Add(new DataColumn("value", typeof(string)));
foreach (string lan in allLan)
{
dr = dt.NewRow();
dr[0] = lan.Split(',')[0];
dr[1] = lan.Split(',')[1];
dt.Rows.Add(dr);
}
DataView dv = new DataView(dt);
return dv;
}
And I call bindLanguage() in page_load.
Here's the code in my aspx :
<asp:DropDownList ID="DropDownList1" runat="server" ForeColor="Black">
</asp:DropDownList>
I had a similar problem .The problem is you are filling your 1st drop-down list in form load and every time some event happens it loads the form i guess u have not kept update panel so again it fills your first drop down and causes selected index changed event to fire which makes your DropDownList1 selected index 0 again and again.
public void bindLanguage() {
if(!Page.IsPostBack)
{
DropDownList1.DataSource = CreateDataSource();
DropDownList1.DataTextField = "language";
DropDownList1.DataValueField = "value";
DropDownList1.DataBind();
}
}
Try this .
Maybe you should add AutoPostBack="false" in the markup-code of the DropDownList.
If this ist not set or true, then the page_load will be triggered everytime you change the object in the dropdown list.
this was always a reason for such issues in my projects.
Change the AutoPostBack property of the dropdownlist to true. Check if error remains.
add this code if (IsPostBack) return; to your Page_Load method.
Related
I am stuck in an issue, tried googling but could not find any solution.
I have created controls dynamically in Page_Load and I have a static button.
When the button is clicked, I need to capture user entry in those controls.
Now when I am trying to access the control using its unique id, error is being returned as the control is not available at runtime. :(
For loop - starts
if (dr["Type"].ToString().Trim() == "DropDown")
{
DropDownList ddl = new DropDownList();
ddl.Id = "ddl" + Convert.ToString(Counter);
ddl.DataTextField = "Text";
ddl.DataValueField = "Value";
ddl.DataSource = ds1;
ddl.DataBind();
ddl.EnableViewState = true;
cell.Controls.Add(ddl);
}
else if (dr["QuestionType"].ToString().Trim() == "TextBox")
{
TextBox txt = new TextBox();
txt.ID = "txt" + Convert.ToString(Counter);
txt.EnableViewState = true;
cell.Controls.Add(txt);
}
row.Cells.Add(cell);
table.Rows.Add(row);
Even if i do a FindControl in Btn_click function, it says that the panel has 0 controls.
var textbox = (TextBox)pnlMidTermFeedback.FindControl("txt5");
textbox is always NULL, although I have a control txt5. I can see it when I do a F12.
Please help.
Dynamically created controls must be recreated on every postback:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Set values and properties of controls specified in markup
...
}
// Create new controls and add them to the panel
...
}
They will then be available in the button event handler, and contain the data entered by the user.
I have a GridView on my page and on a button_OnClick event I'm wanting to add a new row to the grid.
I can add a row to the table using the following code, which works fine, but as I'm binding the DataTable to the grid any previous entries are lost.
string selectedProduct= ddlProducts.SelectedItem.Text;
DataTable dataTable = new DataTable();
dataTable.Columns.Add("Product");
DataRow dataRow;
dataRow = dataTable.NewRow();
dataRow["Product"] = selectedProduct;
dataTable.Rows.Add(dataRow);
grdSelectedProducts.DataSource = dataTable;
grdSelectedProducts.DataBind();
So whilst I understand why this is causing the data loss, I'm not really sure how to get around it.
How can I add a new row to the GridView on each button click whilst retaining the previously added row? The data is not stored anywhere other than the grid itself, so there is no real datasource.
There are options such as Add row to gridview on client side which uses Jquery, but I have read that it isn't a great idea to use that when adding / removing items from the grid. Perhaps that is wrong? Or there is this Add new row to gridview but there isn't much detail there.
You need to store the Products into ViewState (or SessionState or Database) so that it can persist on post back.
For example,
private DataTable ProductDataTable
{
get { return ViewState["ProductDataTable"] as DataTable ?? new DataTable(); }
set { ViewState["ProductDataTable"] = value; }
}
protected void AddRowButton_Click(object sender, EventArgs e)
{
string selectedProduct = ddlProducts.SelectedItem.Text;
// Get the data from ViewState
DataTable dataTable = ProductDataTable;
dataTable.Columns.Add("Product");
DataRow dataRow;
dataRow = dataTable.NewRow();
dataRow["Product"] = selectedProduct;
dataTable.Rows.Add(dataRow);
// Save the data back to ViewState
ProductDataTable = dataTable;
grdSelectedProducts.DataSource = dataTable;
grdSelectedProducts.DataBind();
}
Here is a sample you can try:
DataTable dt = new DataTable();
if (ViewState["CurrentTable"]!=null)
{
dt = (DataTable)ViewState["CurrentTable"];
}
else
{
dt.Columns.Add(new DataColumn("Col1", typeof(string)));
dt.Columns.Add(new DataColumn("Col2", typeof(string)));
}
DataRow dr = null;
dr = dt.NewRow();
dr["Col1"] = "tes";
dr["Col2"] = "test";
dt.Rows.Add(dr);
ViewState["CurrentTable"] = dt;
GridView1.DataSource = dt;
GridView1.DataBind();
Sorry for bad formatting, typed this with my cellphone. Hope it helps! :-)
// OnButten click
function addrow(sender, args) {
// td add as per your column required
$("#GridView1 tbody").append('<tr><td>00001</td><td>Mr.</td><td>LOKESH N</td></tr>');
}
I have a listbox in asp.net and I am binding list Items from database. I have a button named "submit". Now when pages loads I am getting desired values in listbox, but when I am selecting any value and pressing submit button it sets listbox's selected index to -1.
can anyone help me to get proper index value?
<div class="PageRight">
<asp:ListBox ID="ListOfSql" runat="server" SelectionMode="Single" DataTextField="sql_name"
DataValueField="sql_text" Style="margin-left: 0px" Width="205px" EnableViewState="true"
OnSelectedIndexChanged="ListOfSql_SelectedIndexChanged">
</asp:ListBox><br />
<asp:Button ID="btnPreSqlExe" runat="server" Text="Sumbit"
onclick="btnPreSqlExe_Click">
</asp:Button>
</div>
and .cs page is like
protected void btnPreSqlExe_Click(object sender, EventArgs e)
{
txtQuery.Text = ListOfSql.SelectedItem.Value.ToString();
}
To Bind Data in listBox I am using following Code
Private void loadSqlList()
{
if (!IsPostBack)
{
conn.Open();
DataTable dt = new DataTable();
DataSet ds = new DataSet();
string preSql = "select sql_name, sql_text from cn_sql_log order by sql_name";
OracleDataAdapter da = new OracleDataAdapter(preSql, conn);
da.Fill(ds);
ListOfSql.DataSource = ds;
ListOfSql.DataTextField = "Sql_Name";
ListOfSql.DataValueField = "sql_Text";
ListOfSql.DataBind();
ListOfSql.SelectedIndex = 0;
conn.Close();
}
and calling loadSqlList() on page_load
I am inserting data to database when i click submit button data inserted into Database but no changes get reflected in GridView without refreshing the page.
I used DataBind() also.
it is enough to add
YourGridView.DataBind();
in your button onclick event.... no need to bind it also in Page_Load
Do you have any updatepanels?
Just use the Procedure which populates the GridView and then call that Procedure OnClick Event.
Hope it Helps
You can use this code - based on DataBind two times
Nota : you add this DataBind no just in your Page_Load but also in your delegate of click
//Your Insert in your delegate
....
YourGridView.DataBind();
You have to refresh the gridviews data source through whatever means your using, for instance an sql query and then set the datasource to this and then use Gridview1.DataBind();
public void GetData()
{
try
{
SqlConnection connection = new SqlConnection();
connection.ConnectionString = ConfigurationManager.ConnectionStrings["mysql"].ConnectionString;
String sql = "Your Query";
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(sql, connection);
da.Fill(ds);
DataTable dt = new DataTable();
dt = ds.Tables[0];
GridView1.DataSource = dt;
}
catch (SqlException ex)
{
}
catch (Exception e)
{
}
}
Then just use GetData() before you bind the gridview (possibly in your page load event).
You can also do in your rowCommand:
gridView_RowCommand(object sender, GridViewCommandEventArgs e){
gridView.EditIndex = -1; // to cancel edit mode
}
I have an asp.net page that has the following form fields:
Dropdown 1. This drop down receives the data via SQL data source.
Dropdown 2. Based on the selection of the drop down 1, this drop down queries to the database using SQL datasource and is populated.
A panel control that is placed below drop down list 2 and it has a set of the controls.
My problem is there may be a situation when nothing is returned from the datasource of drop down 2, I want to show an Item "No Data found" in the dropdown list 2 and simultaneously hide the panel that is placed below dropdown 2.
Can someone please let me know how this situation can be handled.
Appreciate the help.
Thanks,
Yagya
Add the following code to your dropdownlist1 selected index change event.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
// Run this code when your sql datasource 2 does not return record, you can also place an IfElse condition
DataTable dt = new DataTable();
dt.Columns.Add("ID");
dt.Columns.Add("Value");
DataRow row = dt.NewRow();
row[0] = "-1";
row[1] = "Data Not Found";
dt.Rows.Add(row);
DropDownList2.DataSource = dt;
DropDownList2.DataTextField = "Value";
DropDownList2.DataValueField = "ID";
DropDownList2.DataBind();
}
Updated answer: ( Try this one )
You can also place it in your sqldatasource2 selecting event.
protected void SqlDataSource2_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
if (e.Arguments.TotalRowCount == 0)
{
DataTable dt = new DataTable();
dt.Columns.Add("ID");
dt.Columns.Add("Value");
DataRow row = dt.NewRow();
row[0] = "-1";
row[1] = "Data Not Found";
dt.Rows.Add(row);
DropDownList2.DataSource = dt;
DropDownList2.DataTextField = "Value";
DropDownList2.DataValueField = "ID";
DropDownList2.DataBind();
}
}
The above code will add a Item to your dropdownlist having Text = "Data Not Found"