I am new to ASP.NET, but I need to create checkboxes from a query result. So far here is what I have.
In my code behind...I pull the query that I need and then create a DataTable from that result like so:
DataTable dtLocations = new DataTable();
dtLocations.Columns.Add("ID");
dtLocations.Columns.Add("VALUE");
// Pull locations and add to our datatable
string strConnection = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;
using (SqlConnection dbConn = new SqlConnection(strConnection))
{
SqlDataAdapter dbAdapter = new SqlDataAdapter();
SqlCommand dbCommand = new SqlCommand();
dbConn.Open();
dbCommand.CommandText = #"SELECT location_id, location_desc FROM admin_locations WHERE enabled = 'Y'";
dbCommand.Connection = dbConn;
SqlDataReader dbReader = dbCommand.ExecuteReader(CommandBehavior.CloseConnection);
if (dbReader.HasRows) {
while (dbReader.Read()) {
dtLocations.Rows.Add(new object[] { dbReader["location_id"].ToString(), dbReader["location_desc"].ToString() });
}
}
}
return dtLocations;
I then have a class level var defined as
public DataTable dtLocations = new DataTable();
which I populate using the method above in my Page_Load
protected void Page_Load(object sender, EventArgs e)
{
if (!(IsPostBack))
{
dtLocations = createLocationsDataTable();
}
}
Then in my aspx file (not code behind) I'm doing this to try and create the checkboxes, which needless to say, does not work.
<% foreach (DataRow row in dtLocations.Rows) {%>
<asp:CheckBox ID="idLocationChk" runat="server" Value="<% Response.Write(row["ID"].ToString()); %>" />
<% } %>
Can someone show me how you're supposed to do this in ASP.NET c#? I'll also need to be able to get the value of any that are checked in my code behind when a button on the page is clicked.
When I try using a CheckBoxList like this it tells me I can not use codeblocks here.
<asp:CheckBoxList ID="message_locations" runat="server">
<% foreach (DataRow row in dtLocations.Rows) {%>
<asp:ListItem>TEST</asp:ListItem>
<% } %>
</asp:CheckBoxList>
You can bind a DataTable directly to a CheckBoxList
if (!IsPostBack)
{
CheckBoxList1.DataSource = dtLocations;
CheckBoxList1.DataTextField = "location_desc";
CheckBoxList1.DataValueField = "location_id";
CheckBoxList1.DataBind();
}
Related
After some lengthy experimentation, I discovered that having this line of code on the aspx side:
<EditItemTemplate>
<asp:DropDownList ID="ddl_Project_Owner" runat="server" Width="70px"
DataTextField="Project_Owner" DataValueField="Project_Owner"
SelectedValue='<%# Bind("Project_Owner") %>' >
</asp:DropDownList>
</EditItemTemplate>
caused an index error, but removing the SelectedValue='<%# Bind("Project_Owner") %>' piece allowed the gridview to function properly. The only thing is, when the row goes into edit mode, the dropdown is not filled with the current value. It's blank. I'd like to fill it with the current value.
On the code-behind side, I use this code to fill the dropdown:
protected void DataGrid_ResourceAllocation_EditCommand(object sender, GridViewEditEventArgs e)
{
DataGrid_ResourceAllocation.EditRowStyle.BackColor = System.Drawing.Color.LightYellow;
DataGrid_ResourceAllocation.EditIndex = e.NewEditIndex;
LoadResourceAllocationGrid();
//DataGrid_ResourceAllocation.DataBind();
SqlConnection conn = GetConnection();
int RAC = DataGrid_ResourceAllocation.Rows.Count;
GridViewRow row = DataGrid_ResourceAllocation.Rows[e.NewEditIndex];
//*********************************************************
//******** Fill in all your dropdown lists here ***********
//*********************************************************
DropDownList ddList = row.FindControl("ddl_Project_Owner") as DropDownList;
string ddListVal = ddList.SelectedValue;
//DropDownList ddList = (DropDownList)e.Row.FindControl("ddl_Project_Owner");
if (ddList != null)
{
//bind dropdown-list
string sqlStr = "Select distinct Project_Owner from tblProjectHealth order by Project_Owner";
DataSet ds = new DataSet();
conn.Open();
SqlCommand cmd = new SqlCommand(sqlStr, conn);
SqlDataAdapter ad = new SqlDataAdapter(cmd);
ad.Fill(ds);
ddList.DataSource = ds;
ddList.DataTextField = "Project_Owner";
ddList.DataValueField = "Project_Owner";
ddList.DataBind();
//DataRowView dr = e.Row.DataItem as DataRowView;
//ddList.SelectedItem.Text = dr["category_name"].ToString();
ddList.SelectedValue = ddListVal;
}
}
I tried that "ddListVal" variable because I thought it might work, but it didn't, so you can ignore that.
Can anyone help me get my dropdown to populate with the current value that exists for that field in that record?
This error is due to this : you set selectedValeue befor binding dropdownlist.
you can bind dropdownlist in RowDataBound
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddList= e.Row.FindControl("ddl_Project_Owner") as DropDownList;
if (ddList != null)
{
string sqlStr = "Select distinct Project_Owner from tblProjectHealth order by Project_Owner";
DataSet ds = new DataSet();
conn.Open();
SqlCommand cmd = new SqlCommand(sqlStr, conn);
SqlDataAdapter ad = new SqlDataAdapter(cmd);
ad.Fill(ds);
ddList.DataSource = ds;
ddList.DataTextField = "Project_Owner";
ddList.DataValueField = "Project_Owner";
ddList.DataBind();
}
}
}
I want to have a label and checkbox for each row in from my query.
I needed to get the number of records from my sql query, but I read that SELECT statements will not work with int numberOfRecords = sqlCmd2.ExecuteNonQuery();. So what should I do instead to get the number of records selected from my query (see code below)?
Is this code enough to do what I need to generate labels and checkboxes from a db? Or am I missing something?
Side Note: I do not want to use the Repeater Control. I have tried it, and it isn't robust enough as I program more complicated pages.
ASP
<table>
<tr>
<td>
<asp:Label ID="LabelFormFields" runat="server" Text="Label"></asp:Label>
</td>
<td>
<asp:CheckBoxList ID="CheckBoxListFormFields" runat="server">
</asp:CheckBoxList>
</td>
</tr>
</table>
C#
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection sqlConn2 = new SqlConnection(ConfigurationManager.ConnectionStrings["Events2"].ConnectionString))
{
sqlConn2.Open();
using (SqlCommand sqlCmd2 = new SqlCommand())
{
sqlCmd2.Connection = sqlConn2;
sqlCmd2.CommandType = System.Data.CommandType.Text;
sqlCmd2.CommandText = string.Format("SELECT DisplayName FROM FormField WHERE EventId = 1 AND Visible = 0 ORDER BY ColumnOrder ASC;");
sqlCmd2.ExecuteNonQuery();
int numberOfRecords = //something here;
using (SqlDataReader sqlReader = sqlCmd2.ExecuteReader())
{
while (sqlReader.Read())
{
for (int i = 0; i < numberOfRecords; i++)
{
var PanelFormFields = new Panel();
var LabelFormFields = new Label();
var ListItemFormFields = new ListItem();
LabelFormFields.Text = sqlReader["DisplayName"].ToString();
CheckBoxListFormFields.Items.Add(new ListItem(sqlReader["DisplayName"].ToString(), "C"));
PanelFormFields.Controls.Add(LabelFormFields);
PanelFormFields.Controls.Add(CheckBoxListFormFields);
}
}
}
sqlConn2.Close();
}
}
}
int numberOfRecords = sqlCmd2.ExecuteNonQuery(); //you will get the record numbers; https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery.aspx
But you don't need the numbers here.
your while (sqlReader.Read()) will help to to control the bounds of loop. Based on your description, you don't need this reader. just fill a datatable, then assign it to a datagrid control. as per you want to display a checkbox for each line, you need to make a custom column.
Here is a good sample about how to implement a checkbox and a label in datagrid: http://www.codeproject.com/Articles/7629/Using-CheckBoxes-within-the-DataGrid-control-to-se
use DataTable.Load(IDataReader reader) method to fill a DataTable and then use DataTable.Rows.Count to get number of Records. change your code to something like this:
.
.
sqlCmd2.CommandType = System.Data.CommandType.Text;
sqlCmd2.CommandText = string.Format("SELECT DisplayName FROM FormField WHERE EventId = 1 AND Visible = 0 ORDER BY ColumnOrder ASC;");
int numberOfRecords;
using (System.Data.DataTable dataTable =new System.Data.DataTable())
{
dataTable.Load(sqlCmd2.ExecuteReader());
numberOfRecords = dataTable.Rows.Count;
for (int i = 0; i < dataTable.Rows.Count; i++)
{
System.Data.DataRow dr = dataTable.Rows[i];
var PanelFormFields = new Panel();
var LabelFormFields = new Label();
var ListItemFormFields = new ListItem();
LabelFormFields.Text = dr["DisplayName"].ToString();
CheckBoxListFormFields.Items.Add(new ListItem(dr["DisplayName"].ToString(), "C"));
PanelFormFields.Controls.Add(LabelFormFields);
PanelFormFields.Controls.Add(CheckBoxListFormFields);
}
}
Here is one answer. Please note that I put the code in the Page_Init rather than Page_Load because the Page_Load reloads with every postback and any changes that were not yet written to the database could go away.
protected void Page_Init(object sender, EventArgs e)
{
DataTable dt = GetData();
//int numberOfRecords = dt.Rows.Count;
foreach (DataRow row in dt.Rows)
{
var PanelFormFields = new Panel();
var LabelFormFields = new Label();
var ListItemFormFields = new ListItem();
LabelFormFields.Text = row[0].ToString();
CheckBoxListFormFields.Items.Add(new ListItem(row[0].ToString(), "C"));
PanelFormFields.Controls.Add(LabelFormFields);
PanelFormFields.Controls.Add(CheckBoxListFormFields);
}
}
private DataTable GetData()
{
DataTable dt = new DataTable();
using (SqlConnection sqlConn2 = new SqlConnection(ConfigurationManager.ConnectionStrings["Events2"].ConnectionString))
{
sqlConn2.Open();
string sql = string.Format("SELECT DisplayName FROM FormField WHERE EventId = 1 AND Visible = 0 ORDER BY ColumnOrder ASC;");
using (SqlCommand sqlCmd2 = new SqlCommand(sql, sqlConn2))
{
using (SqlDataAdapter da = new SqlDataAdapter(sqlCmd2))
{
da.Fill(dt);
}
}
}
return dt;
}
Also note that I refactored to use a GetData() method to retrieve the DataTable object and simplify the Page_Init method. I did not close the sqlConn2 object because the using block does this for me. I also used a DataAdapter because it is a simple, fast way to fill a table. Finally, while I kept the numberOfRecords in a commented line to show you how you can get the count, if you need it, it is commented because the foreach loop doesn't need this value.
I have a databound textbox within a gridview which enables the user to easily and quickly bulk update rows. I have tried to use the CustomValidator to validate each textbox against a SQL column but it doesn't behave the way I need it to. The CustomValidator code works properly in the TextChanged event, however it does not behave properly in the ServerValidate event (I understand why). If I leave the code in the TextChanged event handler it still allows the data to be modified when hitting the Update button I created. What can I do to validate each TextBox individually and effectively against the SQL data?
<ItemTemplate>
<asp:TextBox ID="Account" runat="server" AutoPostBack="true" OnTextChanged="Account_TextChanged" Text='<%# Bind("Account") %>'></asp:TextBox>
<asp:CustomValidator ID="CustomValidator1" runat="server" CssClass="CustomValidator" ValidateEmptyText="false" SetFocusOnError="True" Display="Dynamic" ControlToValidate="Account" OnServerValidate="Validate_ServerValidate" ErrorMessage="Custom Validator"></asp:CustomValidator>
</ItemTemplate>
foreach (GridViewRow row in GridView2.Rows)
{
TextBox Account = row.FindControl("Account") as TextBox;
CustomValidator validator = row.FindControl("CustomValidator1") as CustomValidator;
string sAccount = Account.Text;
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString))
using (SqlDataAdapter da = new SqlDataAdapter("SELECT Account Table WHERE Account = #Account", conn))
{
da.SelectCommand.Parameters.Add("#Account", SqlDbType.VarChar);
da.SelectCommand.Parameters["#Account"].Value = sAccount;
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
validator.IsValid = true;
}
else
{
validator.IsValid = false;
}
}
}
I think you would want to do something like
Front Page:
<asp:TextBox runat="server" ID="txtValidateMe"></asp:TextBox>
<asp:CustomValidator runat="server" id="validateTheTextBox" OnServerValidate="validateTheTextBox_OnServerValidate" ControlToValidate="txtValidateMe"/>
Server Side
protected void Page_Load(object sender, EventArgs e)
{
Page.Validate();
if (Page.IsValid)
{
//do something
}
}
protected void validateTheTextBox_OnServerValidate(object source, ServerValidateEventArgs args)
{
using (var conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString))
using (var da = new SqlDataAdapter("SELECT Account Table WHERE Account = #Account", conn))
{
da.SelectCommand.Parameters.Add("#Account", SqlDbType.VarChar);
da.SelectCommand.Parameters["#Account"].Value = args.Value;
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
args.IsValid = true;
}
else
{
args.IsValid = false;
}
}
}
hope this helps
I was able to get this handled by moving the validation logic out of the ServerValidate Event and into an update buttonclick event.
protected void update_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in SomeGrid.Rows)
{
TextBox SomeTextBox = row.FindControl("SomeTextBox") as TextBox;
CustomValidator validator = row.FindControl("SomeValidator") as CustomValidator;
string Account = SomeTextBox.Text;
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
using (SqlDataAdapter da = new SqlDataAdapter("SELECT Account FROM Account WHERE Account = #Account", conn))
{
da.SelectCommand.Parameters.Add("#Account", SqlDbType.VarChar);
da.SelectCommand.Parameters["#Account"].Value = Account;
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
validator.IsValid = true;
}
else
{
validator.IsValid = false;
}
}
}
}
I have a multi level menu with asp.net c# that it gets its items from the database table. my table has items: menuID, menuname, description, parentID. my code is like below.
<asp:Menu ID="menuBar" runat="server" Orientation="Horizontal" Width="80%"
onmenuitemclick="menuBar_MenuItemClick" Height="28px">
</asp:Menu>
and the code behind is:
public void Connect()
{
con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["cnstring"].ConnectionString);
}
private void getMenu()
{
Connect();
con.Open();
DataSet ds = new DataSet();
DataTable dt = new DataTable();
string sql = "Select * from tbl_WebMenu";
SqlDataAdapter da = new SqlDataAdapter(sql, con);
da.Fill(ds);
dt = ds.Tables[0];
DataRow[] drowpar = dt.Select("ParentID=" + 0);
foreach (DataRow dr in drowpar)
{
menuBar.Items.Add(new MenuItem(dr["MenuName"].ToString(), dr["MenuID"].ToString()));
}
foreach (DataRow dr in dt.Select("ParentID >" + 0))
{
MenuItem mnu = new MenuItem(dr["MenuName"].ToString(), dr["MenuID"].ToString());
mnu.Enabled = true;
}
con.Close();
}
I have a page that it's name is description.aspx. when clicking on the one of menu items, I want to redirect to description page and show the description of the selected menu item. I think I should use querystring, like on menuitem click: responce.redirect(description.aspx?ID=something) the problem is that I don't know how to get the ID of the selected item of menu and pass it to the description page.
please help me.
thank you
You can add parameters as Value when adding items to the menu and then retrieve these in on click event handler.
protected void menuBar_MenuItemClick(object sender, MenuEventArgs e)
{
Response.Redirect("SomePAge.aspx?ID=" + e.CommandArgument);
}
This is my CS file for dropdown:
protected void BindDropDownList()
{
DataTable dt = new DataTable();
string connString = System.Configuration.ConfigurationManager.AppSettings["EyeProject"];
SqlConnection conn = new SqlConnection(connString);
try
{
conn.Open();
string sqlStatement = "SELECT FirstName FROM tbl_UserDetails";
SqlCommand sqlCmd = new SqlCommand(sqlStatement, conn);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
DropDownList1.DataSource =dt;
DropDownList1.DataTextField = "FirstName"; // the items to be displayed in the list items
DropDownList1.DataBind();
}
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "No Data Found To display in the DropDown List";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
By using this one iam getting values of table Firstname values now i want to add one more item Called ALLrecords.
How can i add it.
this is my Aspx file
<div class="label">
Select Name:
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
</div>
Try this
DropDownList1.Items.Add(new ListItem("All Record"));
and if you want to add item with value then
DropDownList1.Items.Add(new ListItem("All Record","0"));
//or if you want to add at particular index then
DropDownList1.Items.Insert(0,new ListItem("All Record"));// 0 is index of item
hope this helps.
insert an item at specified index
DropDownListID.Items.Insert(0, new ListItem("Default text", "Default value")
DropDownList1.Items.Insert(0,new ListItem("AllRecords","itsValue_on_dropdownlist")); // use 0 to show "ALLRecords" text on top in dropdownlist
i would suggest that you should bind values to dropdownlist also.
like this -
DropDownList1.DataValueField = "FirstName";
First write onLoad with "addItems" function in dropdownlist declaring tag .aspx file like this:
then create "addItems" function in cs file.
<asp:DropDownList ID="DropDownList1" runat="server" OnLoad="addDeleteItems" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
protected void addItems(object sender, System.EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
ListItem newItem = new ListItem("rose", "i");
ddl.Items.Add(newItem);
}