I have a dropdownlist with few items which bind in code behind. I populate dropdownlist from below query.
Select ID, Name, IsGroup from TempTable
i set DataTextField = "Name" and DataValueField = "ID"
Now i want to disable some items based on "IsGroup" value in DataBound event. How can i access this "IsGroup" column.
For Each item As ListItem In dd.Items
If (What i will compare here = "N") Then
item.Attributes.Add("disabled", "disabled")
End If
Next
Regards
protected void Page_Load(object sender, EventArgs e)
{
var data = GetData();
List<ListItem> items = new List<ListItem>();
foreach (DataRow row in data.Rows)
{
var item = new ListItem()
{
Value = row["Id"].ToString(),
Text = row["Name"].ToString()
};
if (row["IsGroup"].ToString() != "N")
{
item.Attributes.Add("disabled", "disabled");
}
items.Add(item);
}
this.DropDownList1.Items.AddRange(items.ToArray());
}
ref: make drop down list item unselectable
You are doing 2 activities
Fetching data from the database
populating the list item and attaching property/properties to the list item element
Method 1 : Primarily to understand the different operations involved.
class SurroundingClass
{
class Example1
{
public int ID { get; set; }
public string Name { get; set; }
public string IsGroup { get; set; }
}
public void PopulateExample1()
{
// Separate Sections for Database and Dropdown Manipulation
// Database operation
var cs = System.Configuration.ConfigurationManager.ConnectionStrings("CS").ConnectionString;
string sql = "Select ID, Name, IsGroup from TempTable";
SqlConnection conn = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand(sql, conn);
var dr = cmd.ExecuteReader();
List<Example1> e1 = new List<Example1>();
while (dr.Read)
{
var e = new Example1();
e.ID = dr.GetInt32(0);
e.Name = dr.GetString(1);
e.IsGroup = dr.GetString(2);
e1.Add(e);
}
dr.Close();
conn.Close();
// Populate Dropdown
foreach (var i in e1)
{
var li = new ListItem(i.Name, i.ID);
if (i.IsGroup == "Y")
li.Attributes.Add("disabled", "disabled");
ddlExample1.Items.Add(li);
}
}
}
Method 2 : Squeezing the operations in Method 1 together
public void PopulateExample2()
{
// Database Operation and Dropdown Manipulation together
var cs = System.Configuration.ConfigurationManager.ConnectionStrings("CS").ConnectionString;
string sql = "Select ID, Name, IsGroup from TempTable";
SqlConnection conn = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand(sql, conn);
var dr = cmd.ExecuteReader();
while (dr.Read)
{
var li = new ListItem(dr.GetString(1), dr.GetInt32(0));
if (dr.GetString(2) == "Y")
li.Attributes.Add("disabled", "disabled");
ddlExample2.Items.Add(li);
}
dr.Close();
conn.Close();
}
Please note that there can be several variations to the solution, this being only one of them.
Related
I am struggling a bit to populate my dropdown list, can anybody tell me where I am going wrong?
ASPX CODE it keeps looping after getting the connection string - back into the connection string method.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDropDownList();
}
}
private string GetConnectionString()
{
using (DataManager dmgr = new DataManager())
{
dmgr.Connect(ConfigurationManager.AppSettings["ProductionKey"]);
return BindDropDownList();
}
}
public string BindDropDownList()
{
DataTable dt = new DataTable();
SqlConnection connection = new SqlConnection(GetConnectionString());
try
{
connection.Open();
string sqlStatement = "SELECT * FROM Itemseriesmaster";
SqlCommand sqlCmd = new SqlCommand(sqlStatement, connection);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
DropDownList1.DataSource = dt;
DropDownList1.DataTextField = "Description"; // the items to be displayed in the list items
DropDownList1.DataValueField = "ID"; // the id of the items displayed
DropDownList1.DataBind();
}
}
catch (SqlException ex)
{
string msg = "Fetch Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
connection.Close();
}
return AppRelativeTemplateSourceDirectory;
}
DataManager Code - where the code calls into
public DataSet ItemSeriesMaster(int id, string description)
{
object[] args = new object[2] { id, description };
return CallSp(MethodBase.GetCurrentMethod(), args) as DataSet; // i know this is not an sp call.. just testing
}
}
}
I am trying to go to my database and bring out the list.
this code display total of column in each page of grid view footer I want to display total of all columns in all pages footer
if (e.Row.RowType == DataControlRowType.DataRow)
{
string deb = ((Label)e.Row.FindControl("debit")).Text;
string cred = ((Label)e.Row.FindControl("credit")).Text;
decimal totalvalue = Convert.ToDecimal(deb) - Convert.ToDecimal(cred);
amount += totalvalue;
Label lbl = (Label)e.Row.FindControl("lblTotal");
lbl.Text = amount.ToString();
Label lblDebAmount = (Label)e.Row.FindControl("debit");
Label lblCredamount = (Label)e.Row.FindControl("credit");
float debtotal = (float)Decimal.Parse(lblDebAmount.Text);
float credtotal = (float)Decimal.Parse(lblCredamount.Text);
totalPriced += debtotal;
totalPricec += credtotal;
}
if (e.Row.RowType == DataControlRowType.Footer)
{
Label totallblCAmount = (Label)e.Row.FindControl("totallblDebAmount");
Label totallblCredAmount = (Label)e.Row.FindControl("totallblCredAmount");
totallblCAmount.Text = totalPriced.ToString("###,###.000");
totallblCredAmount.Text = totalPricec.ToString("###,###.000");
}
}
Why do it when the row is data bound? Why not do it when you originally bind the data?
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
DataTable dt = Database.GetData();
GridView1.DataSource = dt;
GridView1.DataBind();
//calculate here by manually adding up the debit/credit column from dt
//or do a separate database call that calculates the sum, ex: select sum(debits), sum(credits) from general_ledger
}
}
It makes sense to let the database do the math calculation for you. You wouldn't need to write your own custom calculation code. Just let the database's sum function handle it.
Here's a little more detail.
//Executes a SqlCommand and returns a DataTable
public class GetDataTable(SqlCommand command)
{
var dt = new DataTable();
using (var connection = new SqlConnection("connectionstring"))
{
command.Connection = connection;
connection.Open();
dt.Load(command.ExecuteReader());
}
return dt;
}
//Executes a SqlCommand and returns a scalar of type T
public static T GetScalar<T>(SqlCommand command)
{
using (var connection = new SqlConnection ("connectionstring"))
{
command.Connection = connection;
connection.Open();
var result = command.ExecuteScalar();
if (result is T)
{
return (T)result;
}
else
{
return (T)Convert.ChangeType(result, typeof(T));
}
}
}
//Load the data into the GridView, then get the credit amount and put the value in a label.
//You'll need to adjust the queries to match your schema
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
var tableCommand = new SqlCommand("select columns from table");
GridView1.DataSource = GetDataTable(tableCommand);
GridView1.DataBind();
var creditCommand = new SqlCommand("select sum(stat_amount) from tablename where stat_flag='c'");
var credits = GetScalar<decimal>(creditCommand);
Label1.Text = credits;
}
}
Trying to remove duplicate treenodes when adding data from sql server.
Data is added to tree ok but I can't seem to work out how to remove duplicates of the parent nodes.
public partial class SYS_Main : System.Web.UI.Page
{
public TreeNode testerr = new TreeNode();
private List<string> _isdupe = new List<string>();
private List<string> _dupe = new List<string>();
protected void Page_Load(object sender, EventArgs e)
{
PopulateRootLevel();
TV_Test.CollapseAll();
}
private void PopulateRootLevel()
{
const string connectionString = ("user=;" +
"password=;server =UsersSQL;" +
"Trusted_Connection=yes;" +
"database=System Details; " +
"connection timeout=30");
// connects to sql DB
// sql connection
SqlConnection objConn = new SqlConnection(connectionString);
// sql queries to server
SqlCommand objCommand = new SqlCommand("SELECT Contract, [Server Name],[IP Address] FROM tblServers where Contract !='' AND [SERVER NAME] !='';", objConn);
SqlCommand testquery = new SqlCommand("select s.contract ,COUNT(*)from [System Details].dbo.tblServers s where contract !='' group by Contract having count (*)>1 ;", objConn);
// data adapater holds values of sql queries
SqlDataAdapter da = new SqlDataAdapter(objCommand);
// datatable to hold query data into nodes
DataTable dt = new DataTable();
// data table populated
da.Fill(dt);
//Calls popnodes method and includes dt + nodes for
PopulateNodes2(dt,TV_Test.Nodes);
}
//pop nodes method
private void PopulateNodes2(DataTable dt, TreeNodeCollection nodes)
{
foreach (DataRow dr in dt.Rows)
{
TV_Test.Nodes.Clear();
TreeNode IP = new TreeNode();
IP.Text = dr["IP Address"].ToString();
// new instance of a treenode
testerr = new TreeNode();
testerr.Text = dr["Server Name"].ToString();
testerr.ChildNodes.Add(IP);
TreeNode parent = new TreeNode("Text1");
parent.Text = "keyText1";
parent.Text = (dr["Contract"]).ToString();
_isdupe.Add(parent.Text);
parent.ChildNodes.Add(testerr);
nodes.Add(parent);
string trued;
trued = _isdupe.Distinct().ToString();
if (trued.Equals(parent.Text))
{
TV_Test.Nodes.Remove(parent);
}
else
{
}
}
}
}
}
I think your algorithm is wrong, if you order your query you'll be able to fill the treeview with no duplicate directly.
I load reader to my table like this
connection.Open();
sqlCmd = new SqlCommand(sqlCmd.CommandText, connection);
SqlDataReader sqlReader = sqlCmd.ExecuteReader();
DataTable dt = new DataTable();
sqlReader.Read();
dt.Load(sqlReader);
But it looks like I cannot retrieve the first record of fetch data.
The second problem is when I call the reader several times after that:
string comName = dt.Rows[0]["companyName"].ToString();
//To get address
sqlCmd.CommandText = addr;
sqlCmd.Parameters.AddWithValue("companyName", comName);
using (var addressReader = sqlCmd.ExecuteReader())
{
if (addressReader.Read())
{
Label1.Text = Label1.Text + " " + addressReader["address"].ToString();
}
}
//To get keyProcesses
sqlCmd.Parameters.Clear();
sqlCmd.CommandText = keyProcesses;
sqlCmd.Parameters.AddWithValue("companyName", comName);
using (var keyProcessesReader = sqlCmd.ExecuteReader())
{
if (keyProcessesReader.Read())
{
Label1.Text = Label1.Text + " " + keyProcessesReader.GetString(0);
}
}
But I find out that these reading also may changes the value of my datatable dt above! How could I only load data to dt at the first reading and keep it there without changing any more ?
Ps: In attempt to overcome the second problem, I am trying to store dt values in list
public class CompanyModel
{
public string compnName { get; set; }
public string compnAddress { get; set; }
public string compnKeyProcesses { get; set; }
public string compnStandards { get; set; }
}
then
List<CompanyModel> companies = new List<CompanyModel>();
for(int i = 0; i < dt.Rows.Count; i++)
{
companies.Add(new CompanyModel
{
compnName = dt.Rows[i]["companyName"].ToString(),
compnAddress = dt.Rows[i]["address"].ToString()
});
}
companyRepeater.DataSource = companies;
companyRepeater.DataBind();
Now, how do I access each company name in the list to make query on that name value accordingly, then input the new result to the list?
I tried:
foreach(List<Component> compnName in companies.Contains("companyName")
{
sqlCmd.CommandText = getKey;
sqlCmd.Parameters.AddWithValue("companyName", compnName);
using (var keyReader = sqlCmd.ExecuteReader())
{
if (keyReader.Read())
{
companies.Add(new CompanyModel compnKeyProcesses = keyReader.GetString("key"));
}
}
sqlCmd.CommandText = getstandard;
sqlCmd.Parameters.AddWithValue("companyName", compnName);
using (var standardReader = sqlCmd.ExecuteReader())
{
if (standardReader.Read())
{
companies.Add(new CompanyModel compnStandards = keyReader.GetString("standards"));
}
}
Try this for your first problem
SqlDataAdapter sdr = new SqlDataAdapter(sqlCmd.CommandText, connection);
DataTable dt=new DataTable();
sdr.Fill(dt);
you can display this whole data as a matter of confirmation by taking a datagridview
dataGridView1.DataSource=dt;
I have been given some c# code and have been asked to create a markup (.aspx) file that would go along with it.
I am not asking for help to write the code, but instead, how to go about it.
Here is the code:
public partial class search : Page
{
protected override void OnLoad(EventArgs e)
{
int defaultCategory;
try
{
defaultCategory = Int32.Parse(Request.QueryString["CategoryId"]);
}
catch (Exception ex)
{
defaultCategory = -1;
}
Results.DataSource = GetResults(defaultCategory);
Results.DataBind();
if (!Page.IsPostBack)
{
CategoryList.DataSource = GetCategories();
CategoryList.DataTextField = "Name";
CategoryList.DataValueField = "Id";
CategoryList.DataBind();
CategoryList.Items.Insert(0, new ListItem("All", "-1"));
CategoryList.SelectedIndex = CategoryList.Items.IndexOf(CategoryList.Items.FindByValue(defaultCategory.ToString()));
base.OnLoad(e);
}
}
private void Search_Click(object sender, EventArgs e)
{
Results.DataSource = GetResults(Convert.ToInt32(CategoryList.SelectedValue));
Results.DataBind();
}
private DataTable GetCategories()
{
if (Cache["AllCategories"] != null)
{
return (DataTable) Cache["AllCategories"];
}
SqlConnection connection = new SqlConnection("Data Source=DB;Initial Catalog=Store;User Id=User;Password=PW;");
string sql = string.Format("SELECT * From Categories");
SqlCommand command = new SqlCommand(sql, connection);
SqlDataAdapter da = new SqlDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
Cache.Insert("AllCategories", dt, null, DateTime.Now.AddHours(1), System.Web.Caching.Cache.NoSlidingExpiration);
connection.Dispose();
return dt;
}
private DataTable GetResults(int categoryId)
{
SqlConnection connection = new SqlConnection("Data Source=DB;Initial Catalog=Store;User Id=User;Password=PW;");
string sql = string.Format("SELECT * FROM Products P INNER JOIN Categories C on P.CategoryId = C.Id WHERE C.Id = {0} OR {0} = -1", categoryId);
SqlCommand command = new SqlCommand(sql, connection);
SqlDataAdapter da = new SqlDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
connection.Dispose();
return dt;
}
}
EDIT
In the above code, what is the Results object and is the CategoryList just a listbox?
As Nilesh said this seems like a search page, You can possibly try creating the a Webform using Visual studio which is just drag and drop controls into canvas and that will create the mark up for the controls in the code window.
This code behind seems to be doing the following,
On page load at Get request (when its !Page.IsPostBack) page is going to get categories using GetCategories() and fill the drop down list "CategoryList" with all category names (default selected one being the defaultcategory ID from query string).
The search button takes the dropdown's selected value and calls the GetResults() to get data table to fill the grid view "Results". So you need 3 controls (Dropdown list, Button, Gridview) in the webform with these names..