Display Json Values using webapi - c#

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..

Related

How to insert UTC datetimes to closedXML?

In the c# closedXML plugin, I get this message
Unable to set cell value to 10/27/2017 10:14:23 AM +00:00
c#
public static async Task<string> SaveToExcel(string command, Dictionary<string, object> h, string domain, string sheet_name, string[] headers)
{
SqlConnection myConnection = new SqlConnection(GetConnectionString(domain));
await myConnection.OpenAsync();
SqlCommand myCommand = new SqlCommand(command, myConnection);
foreach (KeyValuePair<string, object> entry in h)
{
myCommand.Parameters.AddWithValue(entry.Key, entry.Value ?? DBNull.Value);
}
System.Diagnostics.Debug.WriteLine(myCommand.CommandText);
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = myCommand;
DataTable dt = new DataTable();
sda.Fill(dt);
// add headers
DataRow dr = dt.NewRow();
for(int i=0; i<headers.Length; i++)
{
//dr[i] = headers[i];
}
//dt.Rows.InsertAt(dr, 0);
string filepath = Excel.SaveExcel(dt, sheet_name);
dt.Dispose();
sda.Dispose();
myCommand.Dispose();
myConnection.Close();
return filepath;
}
public static string SaveExcel(System.Data.DataTable dt, string SheetName)
{
// create the Excel workbook
var wb = new XLWorkbook();
// creates the worksheet
var ws = wb.AddWorksheet(SheetName);
// add data
ws.Cell(1, 1).InsertTable(dt);
// the range for which you want to add a table style
var range = ws.Range(1, 1, dt.Rows.Count, dt.Columns.Count);
// create the actual table
var table = range.CreateTable();
// adjust size
ws.Columns().AdjustToContents();
// apply style
table.Theme = XLTableTheme.TableStyleMedium5;
// save file as temp
string result = Path.GetTempFileName();
wb.SaveAs(result);
return result;
}
How can I fix this?
Thanks

How do i get a json-type response from database?

I have an established connection to database
public string Respond(string sqlExpression)
{
string connectionString = #"Data Source=***;Initial Catalog=***;
User Id=***;Password=***;";
var kek = new List<List<string>>();
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand(sqlExpression, connection);
var reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
var a = new List<string>();
for (int i = 0; i < reader.FieldCount; i++)
{
a.Add(reader.GetSqlString(i).ToString());
}
kek.Add(a);
}
}
reader.Close();
}
return kek.ToJSON();
}
This is what the query returns:database table
What i get from this method, is this: json file
Basically, this is a json wich contains external "[]", and inside there are a bucn of "[]", where there is field data. Though what I want is to get json-file with field names ("name", "synopsis","details") and data.
How do i do this without generating classes?
You should be use System.Web.Script.Serialization.JavaScriptSerializer namespace. You must gather a datatable from your database table. After that you can convert to json with that namespace like below;
public string ConvertDataTableToJson()
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnectionc(connectionString)
{
using (SqlCommand cmd = new SqlCommand(sqlExpression, con))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return serializer.Serialize(rows);
}
}
}
At the end you will get something like this
{"records":[
{
"Id": 1,
"Name": "Foo",
"Surname": "Bar"
}
]}

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();
}
}

How to add values from Dataset to a List?

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;
}

Add an item to combobox before binding data from the database

I had a combobox in a Windows Forms form which retrieves data from a database. I did this well, but I want to add first item <-Please select Category-> before the data from the database. How can I do that? And where can I put it?
public Category()
{
InitializeComponent();
CategoryParent();
}
private void CategoryParent()
{
using (SqlConnection Con = GetConnection())
{
SqlDataAdapter da = new SqlDataAdapter("Select Category.Category, Category.Id from Category", Con);
DataTable dt = new DataTable();
da.Fill(dt);
CBParent.DataSource = dt;
CBParent.DisplayMember = "Category";
CBParent.ValueMember = "Id";
}
}
You could either add the default text to the Text property of the combobox like this (preferred):
CBParent.Text = "<-Please select Category->";
Or, you could add the value to the datatable directly:
da.Fill(dt);
DataRow row = dt.NewRow();
row["Category"] = "<-Please select Category->";
dt.Rows.InsertAt(row, 0);
CBParent.DataSource = dt;
public class ComboboxItem
{
public object ID { get; set; }
public string Name { get; set; }
}
public static List<ComboboxItem> getReligions()
{
try
{
List<ComboboxItem> Ilist = new List<ComboboxItem>();
var query = from c in service.Religions.ToList() select c;
foreach (var q in query)
{
ComboboxItem item = new ComboboxItem();
item.ID = q.Id;
item.Name = q.Name;
Ilist.Add(item);
}
ComboboxItem itemSelect = new ComboboxItem();
itemSelect.ID = "0";
itemSelect.Name = "<Select Religion>";
Ilist.Insert(0, itemSelect);
return Ilist;
}
catch (Exception ex)
{
return null;
}
}
ddlcombobox.datasourec = getReligions();
CBParent.Insert(0,"Please select Category")
You should add "Please select" after you bind data.
var query = from name in context.Version
join service in context.Service
on name.ServiceId equals service.Id
where name.VersionId == Id
select new
{
service.Name
};
ddlService.DataSource = query.ToList();
ddlService.DataTextField = "Name";
ddlService.DataBind();
ddlService.Items.Insert(0, new ListItem("<--Please select-->"));
There are two quick approaches you could try (I don't have a compiler handy to test either one right now):
Add the item to the DataTable before binding the data.
You should be able to simply set CBParent.Text to "<- Please Select Category ->" after you bind the data. It should set the displayed text without messing with the items.
void GetProvince()
{
SqlConnection con = new SqlConnection(dl.cs);
try
{
SqlDataAdapter da = new SqlDataAdapter("SELECT ProvinceID, ProvinceName FROM Province", con);
DataTable dt = new DataTable();
int i = da.Fill(dt);
if (i > 0)
{
DataRow row = dt.NewRow();
row["ProvinceName"] = "<-Selecione a Provincia->";
dt.Rows.InsertAt(row, 0);
cbbProvince.DataSource = dt;
cbbProvince.DisplayMember = "ProvinceName";
cbbProvince.ValueMember = "ProvinceID";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Categories

Resources