Hello everybody and thanks in advance,
Well, I have a DetailsView in my .aspx file and I can't access to a CheckBoxList control placed in the DetailsView's edit template. I've read a lot of threads about this but still can't find a solution. Here's the code...
<asp:DetailsView ID="MyDetailsView" runat="server" Height="50px" Width="125px" AutoGenerateRows="False" DataSourceID="DataMyDetailsView">
...
...
<asp:TemplateField HeaderText="DATA" SortExpression="DATA">
<EditItemTemplate>
<div style="width:400px; height:300px; overflow-y:auto">
<asp:CheckBoxList ID="DataCL" runat="server" DataSourceID="DataEDIT" DataTextField="DATA" DataValueField="ID_DATA">
</asp:CheckBoxList>
</div>
Then, in my .cs file I have this piece of code...
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Do something
}
else
{
CheckItems();
}
}
...
...
public void CheckItems()
{
CheckBoxList DataCL = (CheckBoxList)MyDetailsView.FindControl("DataCL");
using (conexion)
{
conexion.Open();
cmd.Connection = conexion;
DataSet ds = new DataSet();
string cmdstr = "SELECT * FROM DATA";
SqlDataAdapter adp = new SqlDataAdapter(cmdstr, conexion);
adp.Fill(ds);
DataCL.DataSource = ds;
DataCL.DataTextField = "DATA";
DataCL.DataValueField = "ID_DATA";
DataCL.DataBind();
The problem is that when the execution reaches the first line in which the control is called (DataCL.DataSource = ds;), a "NullPointerExeception" is thrown, however I can access easily to controls in ItemTemplate.
Please, can someone help me in this. Thanks again!
You can't do this, because this control is dynamically created after data binding. Instead attach your grid to DataBound (MSDN) event and bind checked box list there
protected void MyDetailsView_DataBound(object sender, EventArgs e)
{
if (MyDetailsView.CurrentMode == DetailsViewMode.Edit)
{
CheckBoxList DataCL = (CheckBoxList)MyDetailsView.FindControl("DataCL");
using (conexion)
{
// your data bound code goes here
}
}
}
Related
I have two pages:
Drop Down List that User picks a Customer Name from and a load button (Panel 1)
Page with Customer Order Information (Panel 2)
On the 2nd page, I have a check box that will show Customer Details in a DetailsView if it is checked.
My issue is when I go to click on the check box, it brings me back to my First Page with the DownDrop List, which is Panel 1. I have to click the load button to see the second panel again and once it's clicked again, it shows the DetailsView which the check box checked.
I have tried everything, this is what my code looks like:
protected void Page_Load(object sender, EventArgs e)
{
// always show first panel when page loads
pnlFirstPage.Visible = true;
pnlSecondPage.Visible = false;
}
protected void btnLoadOrders_Click(object sender, EventArgs e)
{
// hide the first page and continue to second page
pnlSecondPage.Visible = true;
pnlFirstPage.Visible = false;
// if statement to show details view of customer details
if (cbCustomerDetails.Checked == true)
{
dvCustomerDetails.Visible = true;
dvCustomerDetails.DataBind();
pnlFirstPage.Visible = false;
pnlSecondPage.Visible = true;
}
Ok, so the issue/problem is that keep in mind that EVERY post-back will trigger the page load event.
In other words, any button any dropdown/combo box, or ANY code event that triggers a post-back will fire the page load even EACH time, and THEN your button/event code stub runs.
Thus, for really what amounts to the last 200+ web form pages I built?
EVERY page for setup/loading controls, data etc. will have a if not postback code stub on the page load command.
So, say this markup in panel1
<asp:Panel ID="Panel1" runat="server">
<h3>Select Hotel</h3>
<asp:DropDownList ID="cboHotels" runat="server"
DataValueField="ID"
DataTextField="HotelName" Width="198px">
</asp:DropDownList>
<button runat="server" id="btnRun" title="Search"
style="margin-left: 15px"
type="button" class="btn"
onserverclick="btnRun_ServerClick">
<span class="glyphicon glyphicon-home"></span>View
<br />
</button>
</asp:Panel>
<asp:Panel ID="Panel2" runat="server" >
<h3>Hotel Infomration</h3>
<div id="EditRecord" runat="server"
style="float:left;display: normal;border:solid 2px;padding:12px;border-radius:12px">
<h2>Edit Hotel</h2>
<div style="float:left" class="iForm">
<label>HotelName</label>
<asp:TextBox ID="txtHotel" runat="server" f="HOtelName" width="280" /> <br />
bla bla bla for panel2.
so, now my code on startup can be to load up the combo box/dropdown list, and set Panel 1 visible, and panel 2 visible = false.
We have this code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Panel1.Visible = true;
Panel2.Visible = false;
LoadData(); // load our combo box
}
}
void LoadData()
{
SqlCommand cmdSQL =
new SqlCommand("SELECT ID, HotelName FROM tblHotelsA ORDER BY HotelName");
cboHotels.DataSource = MyRstP(cmdSQL);
cboHotels.DataBind();
cboHotels.Items.Insert(0, new ListItem("Select", ""));
}
DataTable MyRstP(SqlCommand cmdSQL)
{
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (cmdSQL)
{
cmdSQL.Connection = conn;
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
And the button to view the details (in panel2), then can look like this:
protected void btnRun_ServerClick(object sender, EventArgs e)
{
if (cboHotels.SelectedIndex > 0)
{
string strSQL = "SELECT * FROM tblHotelsA WHERE ID = #ID";
SqlCommand cmdSQL = new SqlCommand(strSQL);
cmdSQL.Parameters.Add("#ID", SqlDbType.Int).Value = cboHotels.SelectedItem.Value;
DataTable rstData = MyRstP(cmdSQL);
General.FLoader(EditRecord, rstData.Rows[0]);
Panel1.Visible = false;
Panel2.Visible = true;
}
}
And now the results are this:
So, just keep in mind that the REAL first page load has to be inside of that if !IsPostBack stub.
You can think of that code stub the REAL or "first" page load. Thus, loading up a gridview, loading up a combo box, and say setting panel1 visible, and panel2 hidden all typical code that one would place in the real page startup code.
It quite much means you can't really build a working page without taking into account that page-load fires each and every time a event occurs on the page.
In fact, if you adopt a up-date panel, then the above will holds true.
I need to bind some data on view page and the data will fetch from database using c# asp.net.I tried to implement Repeater but i can not know how to bind multiple data inside it.the following is my original view file.
index.aspx:
<div class="wpb_wrapper text-justify">
<asp:Repeater runat="server" ID="rptMissionId" >
<ItemTemplate>
<img src="pic/our-phylosophy.jpg" width="260" height="246" alt="" class="alignleft">
<h1>
<b>Heading</b>
</h1>
<p>
description
</p>
<br/>
<h1>
<b>Heading</b>
</h1>
<p>
description
</p><br>
</ItemTemplate>
</asp:Repeater>
</div>
In the above section one image is present and two set of data also there.Here i need to fetch image from database and set here in image place similarly heading and description in their proper place.My requirement is the last row of table image will set here and the heading,description of last two row will set here.
I am using 3-tire architecture here so please check my below code.
index.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
indexBL objMissionBl = new indexBL();
rptMissionId.DataSource = objMissionBl.getMissionData();
rptMissionId.DataBind();
}
indexBL.cs:
private indexDL objMissionDL = new indexDL();
public DataSet getMissionData()
{
try
{
DataSet ds = objMissionDL.getMissionData();
return ds;
}
catch (Exception e)
{
throw e;
}
}
IndexDL.cs:
SqlConnection con = new SqlConnection(CmVar.convar);
public DataSet getMissionData()
{
con.Open();
try
{
DataSet ds = new DataSet();
string sql = "SELECT TOP 1 * FROM T_Mission_Vission WHERE Heading='Mission' ORDER BY Mission_vision_ID DESC";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataAdapter objadp = new SqlDataAdapter(cmd);
objadp.Fill(ds);
con.Close();
return ds;
}
catch (Exception e)
{
throw e;
}
}
I explained my requirement,if something is wrong or need to add please change it and help me to resolve this.Thanks.
I've searched through a heap of similar questions and done a bit of googling but I cannot find the answer to my problem...
I would like to have a drop down list that is populated by categories in a database...upon selecting a category and hitting submit, a gridview is populated with all the items in that category.
Now, everything works, except whenever I select anything in the category drop down box, it resets straight away to the first selection. So I'm unable to submit any value other than the first to the gridview. I am using autopostback on this item. I have tried to use appenddatabounditems too but that just populated the list with more and more of the same entries...
I would love if anyone could tell me how I can just get the dropdownlist to hold its position after postback?
Selected Category:
<asp:DropDownList ID="ddlCategory" runat="server" AutoPostBack="True" ViewStateMode="Enabled">
</asp:DropDownList>
<asp:Button ID="buttonCategorySubmit" runat="server" OnClick="buttonCategorySubmit_Click" Text="Submit" />
<br />
</div>
<asp:GridView ID="CategoryGridView" runat="server">
</asp:GridView>
<br />
protected void Page_Load(object sender, EventArgs e)
{
PopulateCategorySelection();
}
public void PopulateCategorySelection()
{
SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["ConnString"]);
SqlCommand cmd = new SqlCommand("AllCategories", conn);
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
SqlDataReader ddlValues = cmd.ExecuteReader();
ddlCategory.DataSource = ddlValues;
ddlCategory.DataValueField = "CategoryID";
ddlCategory.DataTextField = "Title";
ddlCategory.DataBind();
conn.Close();
}
protected void buttonCategorySubmit_Click(object sender, EventArgs e)
{
PopulateCategoryTable();
}
public void PopulateCategoryTable()
{
SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["Connstring"]);
SqlCommand cmd = new SqlCommand("SelectCategory", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Selected", ddlCategory.SelectedItem.Value);
conn.Open();
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
adapter = new SqlDataAdapter(cmd);
adapter.Fill(ds);
conn.Close();
CategoryGridView.DataSource = ds.Tables[0];
CategoryGridView.DataBind();
conn.Close();
}
I literally just worked it out everyone...For anyone that has the same issue, you need to check in the page_load method whether the page is loading because a new page is being generated, or information is just being posted-back for the user. If its just postback, we dont want to populate the category dropdown box again. So we use the IsPostBack object in the page_load method, like this:
if (!IsPostBack)
{
PopulateCategorySelection();
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Display DB values in a dropdownlist
I am fetching DB values and displaying them in the Dropdown list. I have country and state drop down lists:
DropDownList1.Items.Add(new ListItem(Session["country"].ToString()));
DropDownList2.Items.Add(new ListItem(Session["state"].ToString()));
I am unable to show the DB values in the DDL. I am getting --select a state--
in the state Dropdown list how to show the DB values in the Dropdown list?
<asp:DropDownList ID="DropDownList2" runat="server" AutoPostBack="True">
<asp:ListItem Value="Select a state" >Select a state</asp:ListItem>
<asp:ListItem Value="value 1" >Maharastra</asp:ListItem>
<asp:ListItem Value="value 2" >Goa</asp:ListItem>
<asp:ListItem Value="value 3" >Kashmir</asp:ListItem>
</asp:DropDownList>
i am cacthing the DB values here and sending them to the next page
if (dt.Rows.Count > 0)
{
DataTable dt1 = new DataTable();
dt1 = bll.getnewid(TextBox1.Text);
if (dt1.Rows.Count > 0)
{
Session["country"] = dt1.Rows[0]["Country"].ToString();
Session["state"] = dt1.Rows[0]["State"].ToString();
Well, you must somehow bind your ddlist to the db results. Looks like this:
ddlist1.DataSource = MyDBAccessClass.GetSomeValues();
ddlist1.DataBind();
Based on more comments... I'll have to play a little roulette and guess what's your intentions. Your code has multiple problems and you've obviously some issues explaining yourself.
If I understood you correctly, you have 2 dropdownlists. You want to populate one with countries and based on the selection, populate the second dropdownlist.
The basic principle looks like this:
DataAccessClass.cs
public class DataAccessClass
{
public static IEnumerable<string> GetCountries()
{
// access the database and retrieve all the values
// returns IEnumerable (a list of items)
}
public static IEnumerable<string> GetStates(string selectedCountry)
{
// access the database and retrieve all the corresponding states
// linq2sql: var states = from o in db.States
// where o.country = selectedCountry
// select o;
// returns IEnumerable (a list of items)
}
}
YourPage.aspx
<asp:DropDownList id="ddlistCountries" runat="server" AutoPostBack="True" /><br />
<asp:DropDownList id="ddlistStates" runat="server" />
YourPage.aspx.cs
public partial class YourPage
{
protected void Page_Init(object sender, EventArgs e)
{
ddlistCountries.SelectedIndexChanged += new EventHandler(ddlist_SelectedIndexChanged);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!isPostBack)
{
PopulateCountries();
ddlistStates.Enabled = false; // no country selected yet!
}
}
protected void PopulateCountries()
{
ddlistCountries = DataAccessClass.GetCountries();
ddlistCountries.DataBind();
ddlist.Items.Insert(0, "Select a country");
}
void ddlist_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlistCountries.SelectedIndex != 0)
{
ddlistStates.DataSource = DataAccessClass.GetStates(ddlistCountries.SelectedValue);
ddlistStates.DataBind();
ddlistStates.Enabled = true;
}
else
{
ddlistStates.Items.Clear();
ddlistStates.Enabled = false;
}
}
}
If you can't understand this, either go back to basics or forget about programming altogether.
DropDownList2.DataSource = {your data source};
DropDownList2.DataTextField = "text column name";
DropDownList2.DataValueField = "data column name of id";
DropDownList2.DataBind();
You need to set your data source to the DDL, then set which values to display, then bind it.
I would suggest to use the dropdownlist like this :
ddl.DataSource = YourDBSource.Get();
ddl.DataBind();
you can then decide what to be displayed here with :
ddl.DataTextField = ...;
or
ddl.DataValueField = ...;
First of all, there is no reason to build your listItem in the .aspx page because you will populate your ddl programmatically.
Secondly I don't know what you mean by 'i am cacthing the DB values here and sending them to the next page'. Just fill the dataSource with the appropriate query on you DB.
If you want to perform more easy filtering / wahtever you want, try to use Linq2SQL.
Additionally, you need to perform this databinding in the *Page_Load()* like this :
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlErreur.DataSource = ...;
ddlErreur.DataTextField = ...;
ddlErreur.DataBind();
}
}
I am trying to do paging of data. Basically I am taking a data and want to show it on multi pages. But it is not working.
I am using Asp.net and C# for coding. I am using mysql as database.
Code is as follows :
ASP code
<asp:DataGrid runat="server" ID="RestData"
AllowPaging="True" PageSize="2"
OnPageIndexChanged="RestData_PageIndexChanged" AllowCustomPaging="True"
PagerStyle-Wrap="False">
<PagerStyle />
</asp:DataGrid>
C# code:
protected void Page_Load(object sender, EventArgs e)
{
BindData();
}
public void BindData()
{
RestData.DataSource = call.GetReader(Convert.ToInt32(AreaData.SelectedValue));
//GetReader is function which returns the data reader of mysql
RestData.DataBind();
}
protected void RestData_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
{
RestData.CurrentPageIndex = e.NewPageIndex;
BindData();
}
Output :
It is displaying two rows(as i have given pagesize 2). But I am not able to see next page.
The query should returns more than 2 rows(it does happen when i use repeater but i am not able to do paging in it.
Please provide some solution ( I was not able to solve my question with any other solution
in this forum so i have created new one)
THANKS in ADVANCE.
Try adding
If(! IsPostBack)
{
BindData();
}
There is an example similar to what you have over here DataGrid custom paging
The below part is more suited for Gridview rather than for DataGrid
You should be subscribing to PageIndexChanging rather than PageIndexChanged event.
PageIndexChanging happens when you click one of the paged buttons and before the grid handles the paging operation
while PageIndexChanged is post the operation.
Also i would put in a check in the page load for the Bind data
The DataGrid must know what to do when you try to change pages.
In your grid (example comes from my project which is in VB, sorry):
<asp:DataGrid ID="MainGrid"
OnEditCommand="MainGrid_Edit"
OnCancelCommand="MainGrid_Cancel"
OnUpdateCommand="MainGrid_Update"
runat="server"
AutoGenerateColumns="False"
AllowSorting="True"
CssClass="DistPortalDataGrid"
AllowPaging="True"
CellPadding="3"
PageSize="25"
onpageindexchanging="MainGrid_PageIndexChanged"
....
Notice the last line...
Now go to the code view and create the following sub:
Protected Sub MainGrid_PageIndexChanged(source As Object, e As DataGridPageChangedEventArgs) Handles MainGrid.PageIndexChanged
MainGrid.CurrentPageIndex = e.NewPageIndex
BindMainGrid() 'rebinds the grid
End Sub
As indicated to Rajuu Parmar, there is no .PageIndex property for the DataGrid. This is correct. The equivalent property for DataGrid is the .CurrentPageIndex. Why Microsoft made them different, I have no idea. While you solved the problem (years ago from the date), I'm hoping that you or someone else finds this useful.
You also need to tell the grid how many items in total there are, by doing something like:
public void BindData() {
RestData.VirtualItemCount = CountTotalItemsInDb();
// ... the rest ....
}
The reason why paging on your datagrid not working was because you had created 'protected' method and it wasn't able to access it.
If the code is change to below, it would have worked. Hope it helps others in need.
public void RestData_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
{
RestData.CurrentPageIndex = e.NewPageIndex;
BindData();
}
Thanks for your help. I got the solution. Just posting the solution
if some one need in future. Finally I got the solution by GridView. It does do paging.
ASP Code
<asp:GridView ID="RestGridData" runat="server"
AllowPaging="True" AutoGenerateColumns="False"
PageSize="2" onpageindexchanging="RestGridData_PageIndexChanging">
</asp:GridView>
CS Code
protected void Page_Load(object sender, EventArgs e)
{
GridBindData(); // on page load
}
public void GridBindData()
{
MySqlConnection Conn; // I am using MySql
myConn = new MySqlConnection("server=localhost;user=root;database=DBName;");
conn.Open();
MySqlCommand cmd = new MySqlCommand("Select Name, address, mobileNo, emailID from user", conn);
MySqlDataReader reader = cmd.ExecuteReader();
// As DataReader can move only in forward it is not useful to use it GridView.
// So convert it to DataTable(or?). It can move in both direction
DataTable dTable = new DataTable();
dTable.Load(reader); // ASP function to convert reader to DataTable
RestGridData.DataSource = dTable;
RestGridData.DataBind();
}
protected void RestGridData_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
RestGridData.PageIndex = e.NewPageIndex;
GridBindData();
}
try this.
protected void G_BgtPersonnel_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
//Next page in the GridView
G_BgtPersonnel.PageIndex = e.NewPageIndex;
BindgrdPersonnal();
}