How to add values from Dataset to a List? - c#

string str = "Select bd_id from [Active]";
ds = new DataSet(str);
da = new SqlDataAdapter(str, con);
da.Fill(ds);
I want to add the dataset that i get that is a List of ID'S in the form:
bd_id
1
2
3
Into a generic LIST as Items
How do i go about doing the same?

Makue use of LINQ to DATATABLE will do you task easily.
DataTable dtDetails = ds.Table[0];
List<int> lstExcelCurrencyCode =
(from dr in dtDetails.AsEnumerable()
select dr.Field<int>("bd_id")).ToList<int>();

SqlDataAdapter sda = new SqlDataAdapter(sql, conn);
DataSet ds = new DataSet();
sda.Fill(ds, "table");
IList<T> lists = GetList<T>(ds.Tables["table"]);
//DataTable Convert To List Method
public List<T> GetList<T>(DataTable table)
{
List<T> list = new List<T>();
T t = default(T);
PropertyInfo[] propertypes = null;
string tempName = string.Empty;
foreach (DataRow row in table.Rows)
{
t = Activator.CreateInstance<T>();
propertypes = t.GetType().GetProperties();
foreach (PropertyInfo pro in propertypes)
{
tempName = pro.Name;
if (table.Columns.Contains(tempName))
{
object value = row[tempName];
if (value.GetType() == typeof(System.DBNull))
{
value = null;
}
pro.SetValue(t, value, null);
}
}
list.Add(t);
}
return list;
}

Related

Select 2 or more columns on DataTable using LINQ

I have a DataTable and I want to select multiple columns on the DataTable that matches the input in the textbox. The code below only selects 1 column.
var result = from data in mDataTable.AsEnumerable ()
where data.Field<string>("Code") == txtCode.Text
select data.Field<string> ("Description");
foreach (var res in result) {
txtxDescription.Text = res.ToString ();
}
How can I select 2 or more columns on DataTable using LINQ?
why not select full rows (DataRow object) and then take all necessary values from them?
var rows = mDataTable.AsEnumerable()
.Where(data => data.Field<string>("Code") == txtCode.Text);
foreach(DataRow r in rows)
{
txtxDescription.Text = r.Field<string>("Description");
}
another option is to project data to anonymous objects:
var result = from data in mDataTable.AsEnumerable ()
where data.Field<string>("Code") == txtCode.Text
select new
{
Description = data.Field<string> ("Description"),
Code = data.Field<string> ("Code")
};
foreach (var res in result)
{
// last value always replace `txtxDescription.Text` ??
txtxDescription.Text = res.Description;
txtxCode.Text = res.Code;
}
public void GridviewBinding()
{
DataSet ds = new DataSet();
string constr = ConfigurationManager.ConnectionStrings["SQLMSDB"].ConnectionString;
string sql = "select * from tbl_users";
using (SqlConnection conn = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(sql))
{
cmd.Connection = conn;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(ds);
gridviewcontrol.DataSource = ds;
gridviewcontrol.DataBind();
ViewState["GridViewBindingData"] = ds.Tables[0];
}
}
}
}
protected void btn_searching_Click(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(txt_search.Text.Trim().ToString()) || !String.IsNullOrWhiteSpace(txt_search.Text.Trim().ToString()))
{
DataTable dt = (DataTable)ViewState["GridViewBindingData"];
var dataRow = dt.AsEnumerable().Where(x => x.Field<dynamic>("UserName") == txt_search.Text);
DataTable dt2 = dataRow.CopyToDataTable<DataRow>();
gridviewcontrol.DataSource = dt2;
gridviewcontrol.DataBind();
}
else
{
GridviewBinding();
}
}

Display Json Values using webapi

I have datatable for fetching my datas from mysql table and i using a foreach loop for getting each value.So i want to convert each value to json and need to display all these values.How can i possible?
My Table
public static DataTable GetAlldata()
{
try
{
string connString = "Server=localhost;database=mytable;uid=myid;";
string query = "SELECT Tname FROM `mytable`.`tdetails`";
MySqlDataAdapter ma = new MySqlDataAdapter(query, connString);
DataSet DS = new DataSet();
ma.Fill(DS);
return DS.Tables[0];
}
catch (MySqlException e)
{
throw new Exception(e.Message);
}
}
public string jsonvalues()
{
string s = "";
RootObject ro = new RootObject();
DataTable dtaltheat = GetAlldata();
foreach (DataRow drow in dtaltheat.Rows)
{
string theatnme = drow["TheatreName"].ToString();
JavaScriptSerializer ser = new JavaScriptSerializer();
s = ser.Serialize(theatnme);
List<string> List = new List<string>();
List.Add(s);
}
return s;
}
This is the present status of my code.But it doesn't work..I am new in this field,so help me..

How to bind Dataset to TreeView in C#.Net [duplicate]

This question already has answers here:
How do you databind to a System.Windows.Forms.Treeview control?
(3 answers)
Closed 8 years ago.
I have created a DataTable with three columns and i am adding rows to that DataTable using Data Rows. Then,I am adding the DataTable to a DataSet. Now, I just want to bind the DataSet to a TreeView.
DataTable dt = new DataTable();
dt.TableName = "Tree";
dt.Columns.Add("Name");
dt.Columns.Add("Project");
dt.Columns.Add("Experience");
List<Profile> list = new List<Profile>
{
new Profile{ Name="Boopathi", Project="NPD", Experience=1},
new Profile{ Name="Stephan", Project="Luxstone", Experience=1},
new Profile{ Name="Sri", Project="DellAsap", Experience=1}
};
var query = from s in list.AsEnumerable()
where s.Experience == 1
select s;
DataSet ds=new DataSet();
DataRow dr = dt.NewRow();
foreach (var t in query)
{
dr["Name"] = t.Name;
dr["Project"] = t.Project;
dr["Experience"] = t.Experience;
}
ds.Tables.Add(dt);
return ds;
Try this
if (ds.Tables.Count > 0)
{
TreeNode root= new TreeNode("Root Node");
foreach (DataRow row in ds.Tables[0].Rows)
{
TreeNode NewNode = new TreeNode(row["Name"].ToString());
root.ChildNodes.Add(NewNode);
}
}
DataTable dt=new DataTable();
DataTable dt1 = new DataTable();
DataSet ds = new DataSet();
ds.Tables.Add(dt);
ds.Tables.Add(dt1);
ds.Relations.Add("children", dt.Columns["GSICCodeID"], dt1.Columns["GSICCodeID"]);
if (ds.Tables[0].Rows.Count > 0)
{
tvSicCode.Nodes.Clear();
Int32 i = 0;
foreach (DataRow masterRow in ds.Tables[0].Rows)
{
TreeNode masterNode = new TreeNode((string)masterRow["Description"], Convert.ToString(masterRow["GSicCodeID"]));
tvSicCode.Nodes.Add(masterNode);
foreach (DataRow childRow in masterRow.GetChildRows("Children"))
{
TreeNode childNode = new TreeNode((string)childRow["SICCodeDesc"], Convert.ToString(childRow["SICCodeID"]));
if (Convert.ToString(ds.Tables[1].Rows[i]["CarrierSICCode"]) != "")
childNode.Checked = true;
masterNode.ChildNodes.Add(childNode);
i++;
}
}
tvSicCode.CollapseAll();
}
here is a simple article also
using telerik :
using System.Data.SqlClient;using Telerik.Web.UI;
namespace RadTreeView_DataBindDataTable
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindToDataTable(RadTreeView1);
}
}
private void BindToDataTable(RadTreeView treeView)
{
SqlConnection connection = new SqlConnection(Properties.Settings.Default.NwindConnectionString);
SqlDataAdapter adapter = new SqlDataAdapter("select CategoryID, CategoryName, Description from Categories", connection);
DataTable dataTable = new DataTable();
adapter.Fill(dataTable);
treeView.DataTextField = "CategoryName";
treeView.DataFieldID = "CategoryID";
treeView.DataValueField = "Description";
treeView.DataSource = dataTable;
treeView.DataBind();
}
}
}

Object reference not set to an instance of an object when I try to join 2 DataTables

I'm trying to join 2 DataTables but I' m getting this error:
Object reference not set to an instance of an object
this is what I'm doing:
DataTable NodeDataTable = new DataTable();
DataTable sdosDataTable = new DataTable();
private DataTable NodedataTable()
{
XmlTextReader xmlreader = new XmlTextReader(Server.MapPath("stuff.xml"));
DataSet ds = new DataSet();
ds.ReadXml(xmlreader);
xmlreader.Close();
if (ds.Tables.Count != 0)
{
NodeDataTable = ds.Tables[22];
}
return NodeDataTable;
}
private DataTable SdosDataTable()
{
XmlTextReader xmlreader = new XmlTextReader(Server.MapPath("stuff.xml"));
DataSet ds = new DataSet();
ds.ReadXml(xmlreader);
xmlreader.Close();
if (ds.Tables.Count != 0)
{
sdosDataTable = ds.Tables[10];
}
return sdosDataTable;
}
and to join both DataTables:
private void JoinNodeSdosDT()
{
DataColumn obj_NodeID, obj_SdosID;
DataSet ds1 = new DataSet();
NodeDataTable = NodeDataTable.Copy();
sdosDataTable = sdosDataTable.Copy();
ds1.Tables.Add(NodeDataTable);
ds1.Tables.Add(sdosDataTable);
obj_NodeID = ds1.Tables["node"].Columns["node_Id"];
obj_SdosID = ds1.Tables["sdos"].Columns["node_Id"];
sdosDataTable.Columns.Add("typeCodee");
DataRelation obj_NodeandSdosRelation = new DataRelation("dept_reln", obj_NodeID, obj_SdosID);
ds1.Relations.Add(obj_NodeandSdosRelation);
foreach (DataRow dr_NodeSods in ds1.Tables["sdos"].Rows)
{
DataRow dr_NondeeeR = dr_NodeSods.GetParentRow("dept_reln");
dr_NodeSods["typeCodee"] = dr_NondeeeR["typeCode"];
}
DataTable dtResult = ds1.Tables["sdos"].DefaultView.ToTable(false, "node_Id", "typeCode", "sdos_Id");
GridView1.DataSource = dtResult;
}
there is some any matching ID what can I do here to resolve my problem.
I removed The datatable Images there is no use of them.
Looks like dr_NondeeeR is null:
DataRow dr_NondeeeR = dr_NodeSods.GetParentRow("dept_reln");
dr_NodeSods["typeCodee"] = dr_NondeeeR["typeCode"];
because for whatever reason GetParentRow is returning null.
As the documentation of DataRow.Item (String) states, accessing a non-existing column should give an ArgumentException. What you are getting is a NullReferenceException. If that happens actually in the line you gave, then I can only assume that
DataRow dr_NondeeeR = dr_NodeSods.GetParentRow("dept_reln");
gives a null reference.

Call dataset from dictionary in foreach loop

How do I call a data set from a dictionary inside of a foreach loop? In the code below .Rows doesn't exist and the dataset is null in the foreach loop.
public class dictWITHdataset
{
public dictWITHdataset()
{
DataSets = new Dictionary<string, DataSet>();
}
public IDictionary<string, DataSet> DataSets { get; private set; }
public DataSet readrows(DataSet dataset)
{
string query = "SELECT * FROM test.dbo.test";
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand(query, conn);
adapter.Fill(dataset);
return dataset;
}
}
I later try to call the dataset from a dictionary in a foreachloop but it claims Rows does exist and its null.
dictWITHdataset dict = new dictWITHdataset();
DataSet data = new DataSet();
dict.DataSets("Dictionary1",data) //not sure if correct way to call data set
foreach (System.Data.DataRow row in dict.DataSets["Dictionary1"].Rows)
{
#:row["id"] + " " + row["name"];
}
You have forgot to call dict.readrows call, thus it only adds an empty dataset. Also, readrows does not need to take a parameter, you can create it in the function.
dictWITHdataset dict = new dictWITHdataset();
DataSet data = new DataSet();
dict.DataSets("Dictionary1",dict.readrows(data))
foreach (System.Data.DataRow row in dict.DataSets["Dictionary1"].Rows)
{
#:row["id"] + " " + row["name"];
}

Categories

Resources