Fill a GridView column data based on the API response - asp.net

I am new to ASP.NET. I want to add a column to GridView dynamically based on the response of an API
id User secretcode
1 u1 {response from the API based on the Id value}
2 u1 {response from the API based on the Id value}
3 u1 {response from the API based on the Id value}
4 u1 {response from the API based on the Id value}
5 u1 {response from the API based on the Id value}
id and User are already in my database table (users), so for each returned row, I want to call API to fill my 3rd column i.e. secretcode. Basically, I am confused with where to use ForEach loop.
This is rough code on which I am working on:
DataTable table = new DataTable();
DataColumn col3 = new DataColumn("Secretcode");
col3.DataType = System.Type.GetType("System.Int");
table.Columns.Add(col3);
row[col3] = {response data from API}
gvTest.DataSource = table;
gvTest.DataBind();

Perhaps something like this
DataTable table = new DataTable();
DataColumn col = new DataColumn("Secretcode");
table.Columns.Add(col);
for(int i = 0; i < table.Rows.Count; i++)
{
// Where 'SomeAPICall()' is calling the API and returning the
// correct data type. If it is returning an object you may want
// to convert it before you attach it to the table
table.Rows[i]["Secretcode"] = SomeAPICall(table.Rows[i]["id"]);
}
gvTest.DataSource = table;
gvTest.DataBind();
Or if you're sold on the idea of the foreach loop:
DataTable table = new DataTable();
DataColumn col = new DataColumn("Secretcode");
table.Columns.Add(col);
foreach(DataRow row in table.Rows)
{
// Where 'SomeAPICall()' is calling the API and returning the
// correct data type. If it is returning an object you may want
// to convert it before you attach it to the table
row["Secretcode"] = SomeAPICall(row["id"]);
}
gvTest.DataSource = table;
gvTest.DataBind();
I prefer using for loops generally because often you want to use the same index number on 2 different collections which you can't really do with a foreach loop. In this case though it won't matter.

Related

Retrieve all rows from DataTable in asp.net

I have created a temporary datatable to store temporary data before send it to database. But after creating that now i want to fetch all the rows from this temporary datatable and save them to data base. For this i loop my datatable using foreach loop
foreach(DataRow r in dt.Rows)
{
string Fname = dt.Rows[0]["Name"].ToString();
string cType = dt.Rows[0]["ContentType"].ToString();
byte[] ePic = (byte[])dt.Rows[0]["pic"];
BAL.saveEventPictures(Convert.ToInt32(lblEventID.Text), Fname, cType, ePic);
}
The problem is that it only fetch the data of first row again and again for the whole loop count. Like if I have 4 datarows with different information, then this will store the data of 1st row in the database for 4 times. What mistake am i doing?
dt.Rows[0] means you are always accessing the first row of your DataTable.You need to use a for loop instead of a foreach and use i to access each index of your table:
for (int i = 0; i < dt.Rows.Count; i++)
{
string Fname = dt.Rows[i]["Name"].ToString();
string cType = dt.Rows[i]["ContentType"].ToString();
byte[] ePic = (byte[])dt.Rows[i]["pic"];
BAL.saveEventPictures(Convert.ToInt32(lblEventID.Text), Fname, cType, ePic);
}
You can use for loop to fetch all value regarding their columns in datatable to assign value in their variables so you can use this way. Because if you use hard coded index of datatable rows then it should fetch only single data every time.
Here i is index of rows and column name to get value from rows. So use dynamically based indexing use for get all records.
for (int i = 0; i < dt.Rows.Count; i++)
{
string Fname = dt.Rows[i]["Name"].ToString();
string cType = dt.Rows[i]["ContentType"].ToString();
byte[] ePic = (byte[])dt.Rows[i]["pic"];
BAL.saveEventPictures(Convert.ToInt32(lblEventID.Text), Fname, cType, ePic);
}

Dynamodb is it possible to query all values in a column

I am trying to work out the best method for querying all the values down a column. Should I set it as a GSI (it is currently). is it possible with a query or would I need to to do a scan?
Thanks for your help
You have to do a scan if you are not filtering by key. Here is the sample code to scan the index and get all the values.
List<String> categoryList = new ArrayList<>();
DynamoDB dynamoDB = new DynamoDB(dynamoDBClient);
Table table = dynamoDB.getTable("Music");
Index index = table.getIndex("Secondary Index Name");
ItemCollection<ScanOutcome> items = null;
ScanSpec scanSpec = new ScanSpec().withSelect(Select.SPECIFIC_ATTRIBUTES).withAttributesToGet("Category");
items = index.scan(scanSpec);
Iterator<Item> pageIterator = items.iterator();
while (pageIterator.hasNext() ) {
categoryList.add(pageIterator.next().getString("Category"));
}

Displaying LINQ query results in a DataGridView with a DataTable

I have a function which contains a LINQ query and returns the results as a DataTable. I'm having trouble using the returned DataTable to populate a DataGridView. The query should be returning some data, but the table looks to be coming back empty. My function is as follows:
public static DataTable GetEmployeeTimesheets(int employeeId)
{
DataTable table = new DataTable();
using (PTMS_DataEntities entities = new PTMS_DataEntities())
{
var timesheets = from timesheet in entities.Timesheets
join timesheetTask in entities.Timesheet_Task
on timesheet.Id equals timesheetTask.Timesheet_Id
join task in entities.Tasks
on timesheetTask.Task_Id equals task.Id
join project in entities.Projects
on task.Project_Id equals project.Id
join department in entities.Departments
on project.Department_Id equals department.Id
where timesheet.Employee_Id == employeeId
select new
{
date = timesheet.Date,
taskName = task.Name,
projectName = project.Name,
projectDesc = project.Description,
departmentName = department.Name,
taskEstimatedHours = task.Estimated_Hours,
timesheetHours = timesheetTask.Hours
};
table.Columns.Add("date");
table.Columns.Add("taskName");
table.Columns.Add("projectName");
table.Columns.Add("projectDesc");
table.Columns.Add("departmentName");
table.Columns.Add("taskEstimatedHours");
table.Columns.Add("timesheetHours");
foreach (var item in timesheets)
{
table.Rows.Add(item.date, item.taskName, item.projectName,
item.projectDesc, item.departmentName, item.taskEstimatedHours,
item.timesheetHours);
}
}
return table;
}
The code populating the DataGridView is as follows:
TimesheetGrid.DataSource = EmployeeManager.GetEmployeeTimesheets(employeeId);
TimesheetGrid.DataBind();
Am I doing something wrong in the function / LINQ query itself, or am I just not populating the DataGridView correctly?

how to group a query in linq to Entity

I am using linq to Entity to retrieve data from to different tables by joining them, but I also want to group them by the field problemDesc in order to get rid of unnecessary duplicate entries for the same problem.
here is the code:
using (AssistantEntities context = new AssistantEntities())
{
var problems = context.tblProblems;
var customers = context.tblCustomers;
var query =
from problem in problems
join customer in customers
on problem.CustID equals customer.custID
where problem.IsActive == true
orderby customer.isMonthlyService == true descending
select new
{
problemID = problem.problemID,
ProblemCreateDate = problem.ProblemCreateDate,
CustID = problem.CustID,
name = customer.name,
isMonthlyService = customer.isMonthlyService,
StationName = problem.StationName,
problemDesc = problem.problemDesc,
LogMeIn = problem.LogMeIn
};
return query.ToList();
}
I am doing query.toList() in order to use that list in a gridview as a dataSource.
and if it possible, also add a field that count the duplicate problems.
You have plenty of examples in the following link.
LINQ - Grouping Operators

Format XML data to display on a gridview

I am trying to format XML data to display on a grid.
Page1.aspx. This inserts XML data stored a xmldatatype:
WorkHistory workhis = js.Deserialize<WorkHistory>(json);
XmlDocument work = (XmlDocument)JsonConvert.DeserializeXmlNode(json, "root");
objBLL.insert_XMLWork(work, Convert.ToInt64(ui.id));
Page2.aspx retrieves it and display on a grid:
DataTable FBWorkDt = objBLL.get_FacebookWork(FacebookUserId);
GrdWork.DataSource = FBWorkDt;
GrdWorkPub.DataBind();
get_FacebookWork(select workinfo from Fprofiles where Userid = FacebookUserId)
returns a DataTable
It displays in this format exactly.
WorkInfo
<root><work><employer><id>208571635850052</id><name>Netizen Apps</name></employer></work><id>1076483621</id></root>
How do I make a normal display instead of XML format?
Thanks
Sun
It depends a good deal on the shape of the DataTable you're returning, but assuming you want the display to be something like this:
`ID Name
-------------------- ---------------------
208571635850052 Netizen Apps`
You could use LINQ:
DataTable FBWorkDt = objBLL.get_FacebookWork(FacebookUserId);
var query = from x in FBWorkDt.AsEnumerable()
select new {
id = x.ID,
name = x.Name
};
GrdWork.DataSource = query.ToList();
GrdWorkPub.DataBind();
I haven't tried the code out, so there may be minor syntatic changes, but essentially what it's doing is:
Use LINQ to get a collection of a new anonymous type that has one entry per row with the id and name from the table. You have to use AsEnumerable() [contained in System.Data.DataSetExtensions].
Convert the LINQ result set to a List via .ToList() and bind it to the GridView.
If you can post a little more information - what exactly you mean by display, and the expected shape of the returned DataTable (i.e., what the columns in each row are) we can give you a better answer.
UPDATE
If you're storing the XML document above in your datastore and that is being returned in the table, try this code:
DataTable FBWorkDt = objBLL.get_FacebookWork(FacebookUserId);
XDocument xDoc = XDocument.Load(FBWorkDt.Rows[0][0].ToString());
var query = from x in xDoc.Descendants("employer")
select new
{
id = (string)x.Element("id"),
name = (string)x.Element("name")
}
GrdWork.DataSource = query.ToList();
GrdWorkPub.DataBind();
Same basic principal as above, except this time your querying over an XDocument instead of a DataTable.

Resources