I have:
1 Datatable - EmployeeAccess &
1 View - View_HCM
Both have the same column (EmpNo), View_HCM have 1000+ data where EmployeeAccess have only 4 data.
View_HCM has email address field and EmployeeAccess has none. I need to get email address from View_HCM according to the 4 data.
public List<EmployeeAccess> EmployeeAccess2()
{
EmployeeAccess EA = new EmployeeAccess();
View_HCM VH = new View_HCM();
var x = from b in contxt.View_HCM
where b.EmpNo == EA.EmpNo
select b.EmailAddress;
return x.ToList();
}
I'm getting this error:
Cannot implicitly convert type 'Systems.Generic.Collections.String<string>' to ... '< list >'
Your return type is wrong.
To fix the errror change the returned type:
public List<string> EmployeeAccess2()
{
EmployeeAccess EA = new EmployeeAccess();
View_HCM VH = new View_HCM();
var x = from b in contxt.View_HCM
where b.EmpNo == EA.EmpNo
select b.EmailAddress;
return x.ToList();
}
And to show the email address in the gridview you can do like this
Define a class with a single named field:
public class EmailRecord
{
public string EmailAddress{ get; set; }
}
public List<EmailRecord> EmployeeAccess2()
{
EmployeeAccess EA = new EmployeeAccess();
View_HCM VH = new View_HCM();
var x = from b in contxt.View_HCM
where b.EmpNo == EA.EmpNo
select new EmailRecord
{
EmailAddress = b.EmailAddress
};
return x.ToList();
}
Bind your grid
gridEmployeeAccess.DataSource = TAClass.EmployeeAccess2(); gridEmployeeAccess.DataBind();
In aspx:
<asp:GridView ID="gridEmployeeAccess" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="EmailAddress" headertext="Email Address"/>
</Columns>
</asp:GridView>
Related
I need help on part of this code. I'm using a checkbox column in my DataGridView control. When I retrieve my data record, if a value exists then the checkbox should be checked, and if not it should remain unchecked. How to I accomplish that on a DataGridView with this kind of logic?
using (DataContext dtContext = new DataContext())
{
var query = (from i in dtContext.materialTBheader where i.proj == Proj_id select i);
foreach (var r in query)
{
if (!string.IsNullOrEmpty(r.materialheader_id.ToString()))
{
string[] row = { r.materialheader_id.ToString(), r.materialname, r.description, string.Format("{0:n2}", r.totalAmount), GetCount(r.materialname, txtMainProjectHeader_id, Convert.ToDecimal(r.totalAmount)), "", -- cell checkbox if record exist true checked if not false uncheck };
dGVMaterialHeaderList.Rows.Add(row);
}
}
}
It dosen't need to add your rows by foreach, use DataSource Property
Suppose you have a List of Person and you want to show in dataGridview, you have to option
1)add your column to data grid in visual studio properties window
2)add your column with coding
then map your data to grid
here is an simple example to help yo
public class Person
{
public int Id { get; set; }
public string LastName { get; set; }
public bool Married { get; set; }
}
private void Form1_Load(object sender, EventArgs e)
{
//your data from ef
var myData = new List<Person>
{
new Person{Id=1,LastName="A1",Married =true},
new Person{Id=1,LastName="A2",Married =false},
new Person{Id=1,LastName="A3",Married =true},
};
//your columns
var idColumn = new System.Windows.Forms.DataGridViewTextBoxColumn
{
Name = "Id",
HeaderText = "Id",
DataPropertyName = "Id"
};
var lastNameColumn = new System.Windows.Forms.DataGridViewTextBoxColumn
{
Name = "LastName",
HeaderText = "LastName",
DataPropertyName = "LastName"
};
var marriedColumn = new System.Windows.Forms.DataGridViewCheckBoxColumn
{
Name="Married",
HeaderText="Married",
DataPropertyName= "Married"
};
// add your columns to grid
dGVMaterialHeaderList.Columns.Add(idColumn);
dGVMaterialHeaderList.Columns.Add(lastNameColumn);
dGVMaterialHeaderList.Columns.Add(marriedColumn);
dGVMaterialHeaderList.AutoGenerateColumns = false;
//bind your data
dGVMaterialHeaderList.DataSource = myData;
}
In your case the answer is something like below:
using (DataContext dtContext = new DataContext())
{
var query = (from i in dtContext.materialTBheader where i.proj == Proj_id select i).ToList();
var gridData = query.Select(r=>new
{
materialheader_id = r.materialheader_id.ToString(),
r.materialname,
r.description,
totalAmount = string.Format("{0:n2}", r.totalAmount),
Count = GetCount(r.materialname, txtMainProjectHeader_id, Convert.ToDecimal(r.totalAmount)),
isExist = !string.IsNullOrEmpty(r.materialheader_id.ToString())?true:false
}).ToList();
dGVMaterialHeaderList.DataSource = gridData;
}
I don't know your data structure but I know this is not best approach you choose
I hope this can help you
i have a view where i get data from a table named 'PromotionHistory'. But in my table i stored ID of Designation. In Designation table i have DesignationName field and DesignationID. Both table have relation. I am using Web Api.
My code-
[HttpGet]
[Route("api/EmployeeApi/GetPromotionReport/")]
public object GetPromotionReport()
{
List<PromotionHistory> finalData;
//var proReport = db.PromotionHistories.Include(e => e.Designation).Include(e => e.Employee);
IEnumerable<PromotionHistory> pro = (from st in db.PromotionHistories select st).ToList();
foreach (PromotionHistory proH in pro)
{
var preD = proH.PreviousDesigID;
var currentD = proH.CurrentDesigID;
var preDName=(from dd in db.Designations where dd.DesignationID==preD select new{dd.DesignationName}).FirstOrDefault() ;
var CurrentDName=(from dd in db.Designations where dd.DesignationID==currentD select new{dd.DesignationName}).FirstOrDefault();
var cc = (from proHis in db.PromotionHistories
select new
{
proHis.PromotionID,
proHis.EmployeeID
}
).ToList();
finalData.AddRange(cc);
finalData.Add(preDName);
}
I want to get DesignationName instead of ID for the two field (previousPost, Current Post-see image)
How can i make Linq or SQL query in ASP Web Api as i am using Ajax.
What i want::
PromotionID ,EmplyeeID ,PromotionDate, Previous Designation , Current Designation
You can add another class, and return list of the new class. like this
public object GetPromotionReport()
{
List<PromotionHistorywithNames> finalData;
finalData = (from st in db.PromotionHistories
select new PromotionHistorywithNames
{
PromotionID = st.PromotionID,
EmployeeID = st.EmployeeID,
PreviousPost = (from dd in db.Designations where dd.DesignationID == st.Promotion select dd.DesignationName).FirstOrDefault(),
CurrentPost = (from dd in db.Designations where dd.DesignationID == st.currentD select dd.DesignationName).FirstOrDefault()
}).ToList();
return finalData;
}
and the class like this
public class PromotionHistorywithNames{
public int PromotionID{set;get;}
public int EmployeeID{set;get;}
public DateTime Promotion{set;get;}
public string PreviousPost{set;get;}
public string CurrentPost{set;get;}
}
I solved my annonymous type problem by this: It can be done without model class
[HttpGet]
[Route("api/MemberApi/GetMembersWithLink/")]
public object GetMembersWithLink()
{
var member = (from members in db.Members
where members.Status == 1
select new
{
members.MemberName,
members.Position,
members.Phone,
members.Picture,
members.MotherName,
members.Village,
members.Email,
linkName = (from gg in db.Members where gg.MemberID== members.Link select gg.MemberName).FirstOrDefault()
}).ToList();
return member.AsEnumerable();
}
I have anonymous type list. I want to get data from this list
My code is as bellow
var data = from EP in DbContext.EmployeeProfesionalDtls
join DM in DbContext.DesignationMasters on EP.DesigId equals DM.DesigId
join DP in DbContext.DepartmentMasters on new { DepId = EP.DepId } equals new { DepId = DP.DeptId }
select new
{
ProfId = EP.ProfId,
EmpId = EP.EmpId,
EntryDate = DM.EntryDate,
DeptName = DP.DeptName,
DepartmentUnitID = DP.UnitId,
DepartmentEntryDate = DP.EntryDate
}
"data" have anonymous type list. I wants to get data from this anonymous type list.
You have to take a view model i.e. a class to send it to view :
var data = from EP in DbContext.EmployeeProfesionalDtls
join DM in DbContext.DesignationMasters on EP.DesigId equals DM.DesigId
join DP in DbContext.DepartmentMasters on new { DepId = EP.DepId } equals new { DepId = DP.DeptId }
select new Test()
{
ProfId = EP.ProfId,
EmpId = EP.EmpId,
EntryDate = DM.EntryDate,
DeptName = DP.DeptName,
DepartmentUnitID = DP.UnitId,
DepartmentEntryDate = DP.EntryDate
}
where Test is a class with these properties.
I want to add the content of the combobbox into my database, but it doesn't work. The content of my combobox is from the table 'Categories' who's joined with the table 'Products'. I've tried many things I have errors of conversion :
Here's my code :
Product p = new Product();
p.ProductName = txtNom.Text.Trim();
p.ProductDescription = txtDesc.Text.Trim();
p.ProductQuantityUsed = Convert.ToInt32(numQteUsed.Value);
p.ProductQuantityNew = Convert.ToInt32(numQteNew.Value);
p.CategoryID = cboCat.SelectedText.ToString();
db.Products.Add(p);
db.SaveChanges();
//Combobox
public void FillCbCategories()
{
SamsonEntities db = new SamsonEntities();
cboCat.Items.Clear();
var listCat = (from cats in db.Categories
select new CategoryDisplay()
{
CategoryID = cats.CategoryID,
CategoryName = cats.CategoryName
}).ToList();
for(var i=0;i<listCat.Count;i++)
{
cboCat.Items.Add(listCat[i]);
}
}
Judging by your comments, your combobox is not binded correctly to data you send to it.
You could try setting ValueMember and DisplayMember:
cboCat.ValueMember = "CategoryID";
cboCat.DisplayMember = "CategoryName";
in your method, like this:
public void FillCbCategories()
{
SamsonEntities db = new SamsonEntities();
cboCat.Items.Clear();
var listCat = (from cats in db.Categories
select new CategoryDisplay()
{
CategoryID = cats.CategoryID,
CategoryName = cats.CategoryName
}).ToList();
for(var i=0;i<listCat.Count;i++)
{
cboCat.Items.Add(listCat[i]);
}
cboCat.ValueMember = "CategoryID";
cboCat.DisplayMember = "CategoryName";
}
Ok here is the scenario. I have created a completely data driven Radgrid with only 2 static buttons on the page, Save and Cancel. The Radgrid is created dynamically, as well as all the data in the grid (from MS SQL). Here is the tricky part, I have a template column that will contain a control. The type of control is determined again by the data in SQL. I.e., data is 6, I need to return a RadTextBox populated with data from SQL, 5 = RadComboBox, also populated... you get the jist. I have a total of 50 records, so I have around 50 controls, all populated with data which can change and be saved. That is the hard part. I have been stuck for 2 days trying to figure out how to get to the RadGrids cell level, find the control, determine what type of control it is, retrieve the lastest data from that control and save it back out to the Database. The code works, I just need help finding the controls and saving the data...
I need to hit the Save button, which in turn gets all the data and saves it to db. I cannot show you all my code because the codebehind is close to 600 lines. but I will demonstrate with one.
I am giving the controls IDs based on a unique value from that row, so ID="c" = x where x is the unique value.
page.aspx
<form id="formUnionActivityProtestor" runat="server">
<asp:HiddenField ID="hiCaseId" runat="server" />
<asp:HiddenField ID="hiCaseSequence" runat="server" />
<telerik:RadScriptManager runat="server" ID="RadScriptManager1" ScriptMode="Release">
</telerik:RadScriptManager>
<div id="headDiv">
<h2>Blah blah blah</h2>
<h3>blah zeyblah</h3>
<telerik:RadButton runat="server" ID="btnSaveUA" CausesValidation="true" OnClick="btnSaveUA_Click"
Text="Save Union Activity" Skin="Web20" Font-Size="12px" Width="145" Font-Bold="true">
</telerik:RadButton>
<telerik:RadButton runat="server" ID="btnCancel" OnClientClicking="ReadOnly"
Text="Cancel Changes" Skin="Web20" Font-Size="12px" Width="145" Font-Bold="true">
</telerik:RadButton>
</div>
<hr />
<div id="gridContainer" runat="server">
<asp:PlaceHolder runat="server" ID="PlaceHolder1"></asp:PlaceHolder>
</div>
</form>
page.aspx.cs
protected void Page_Init(object sender, System.EventArgs e)
{
radgrid = new RadGrid();
radgrid.ID = "radgrid";
radgrid.PreRender += new EventHandler(radUAGrid_PreRender);
PlaceHolder1.Controls.Add(radgrid);
this.radgrid.NeedDataSource += new GridNeedDataSourceEventHandler(this.grid_NeedDataSource);
radgrid.ItemDataBound += new Telerik.Web.UI.GridItemEventHandler(this.radgrid_ItemDataBound);
radgrid.MasterTableView.DataKeyNames = new string[] { "q_SortValue" };
radgrid.MasterTableView.AutoGenerateColumns = false;
radgrid.MasterTableView.ShowHeader = false;
radgrid.BorderColor = System.Drawing.Color.Gray;
GridBoundColumn boundColumn;
boundColumn = new GridBoundColumn();
boundColumn.ItemStyle.Width = 600;
boundColumn.ItemStyle.CssClass = "prompt";
boundColumn.DataField = "q_Prompt";
radgrid.MasterTableView.Columns.Add(boundColumn);
GridTemplateColumn templateColumn = new GridTemplateColumn();
templateColumn.ItemTemplate = new TemplateColumn("q_QuestionnaireTypeID");
//templateColumn.ItemStyle.Width = 0;
templateColumn.DataField = "q_QuestionnaireTypeID";
templateColumn.UniqueName = "q_QuestionnaireTypeID";
radgrid.MasterTableView.Columns.Add(templateColumn);
boundColumn = new GridBoundColumn();
boundColumn.Display = false;
boundColumn.ItemStyle.CssClass = "hidecol";
boundColumn.DataField = "t_QuestionnaireTypeDescription";
radgrid.MasterTableView.Columns.Add(boundColumn);
}
public partial class TemplateColumn : System.Web.UI.Page ,ITemplate //adding template fields
{
string fieldName = "";
int controlTypeID = 0;
DataTable dt;
int counter = 1;
UnionActivity refMgr = new UnionActivity(Global.ICEConnectionString);
public TemplateColumn(string fieldName)
{
this.fieldName = fieldName;
}
public int getQuestionTypeID(int count)
{
int k = (from DataRow dr in dt.Rows.OfType<DataRow>()
where (int)dr["q_SortValue"] == count
select (Int32)dr["q_QuestionnaireTypeID"]).FirstOrDefault();
return k;
}
public void InstantiateIn(Control container)
{
if (counter == 1)
{
dt = UnionActivityDataTable.dt;
}
controlTypeID = getQuestionTypeID(counter);
if (controlTypeID == 5)
{
int QID = (from DataRow dr in dt.Rows.OfType<DataRow>()
where (int)dr["q_SortValue"] == counter
select (int)dr["q_QuestionnaireInstanceID"]).FirstOrDefault();
int QQID = (from DataRow dr in dt.Rows.OfType<DataRow>()
where (int)dr["q_SortValue"] == counter
select (int)dr["q_QuestionnaireInstanceQuestionID"]).FirstOrDefault();
string answer = (from DataRow dr in dt.Rows.OfType<DataRow>()
where (int)dr["q_SortValue"] == counter
select (string)dr["a_Answer"]).FirstOrDefault();
DataTable dt1;
dt1 = getDropDownList(QID, QQID);
RadComboBox cb = new RadComboBox();
foreach (DataRow row in dt1.Rows)
{
RadComboBoxItem item = new RadComboBoxItem();
item.Text = row["DisplayValue"].ToString();
item.Value = row["DDID"].ToString();
if (answer == item.Text)
{
cb.SelectedValue = item.Value;
}
cb.Items.Add(item);
item.DataBind();
}
string x = (from DataRow dr in dt.Rows.OfType<DataRow>()
where (int)dr["q_SortValue"] == counter
select Convert.ToString((int)dr["a_QuestionnaireInstanceQuestionID"])).FirstOrDefault();
cb.ID = "c" + x;
container.Controls.Add(cb);
}
}
DataTable getDropDownList(int QID, int QQID)
{
DataTable dt2 = new DataTable();
try
{
using (refMgr)
{ //retrieving qicr_QuestionnaireInstanceCaseReferenceID
using (DataTable getDropDownData = refMgr.DynamicDropDownData(QID, QQID))
{
if (getDropDownData != null)
{
dt2 = getDropDownData;
}
}
}
}
catch (Exception ex)
{
}
return dt2;
}
}
after page load I look at the source and this is the insert for the combobox...
<td class="rcbInputCell rcbInputCellLeft" style="width:100%;">
<input name="radgrid$ctl00$ctl22$c12" type="text" class="rcbInput radPreventDecorate" id="radgrid_ctl00_ctl22_c12_Input" value="Kiosk" readonly="readonly" />
</td>
I need to attach a method to the save button, but I dont know the first place to start. Telerik is good about getting the page built dynamically, but not saving the data back out. (or even finding the controls...)
I have seen something like this done for survey generation. The only difference is that it wasn't using a Grid. Is there a reason why you need to use a grid rather than just dynamically building the controls on the page?
I can suggest a way so that you can easily obtain the values from dynamic controls.
You can introduce an interface that all your survey controls need to implement.
interface ISurveyControl
{
// expose some common properties
int QuestionID {get; set;}
object Value {get; set;}
// and others as required
}
Then create an extension for every type of control that you need in your survey
public class SurveyTextBox : RadTextBox, ISurveyControl
{
public int QuestionID {get; set;}
public object Value
{
get { return Text; }
set { Text = value.ToString(); }
}
}
public class SurveyComboBox : RadComboBox, ISurveyControl
{
public int QuestionID {get; set;}
public object Value
{
get { return SelectedValue; }
set { SelectedValue = value.ToString(); }
}
}
Make sure you use these extended controls when building the survey and populate the common properties correctly.
Then all you need is a helper function to find all ISurveyControl controls from a container, regardless of whether it's a grid or a page.
List<ISurveyControl > FindSurveyControls(Control container)
{
// you can use linq to find all ISurveyControl within the container
// you may need to make this recursive as well
}
You can then iterate through the controls on save, knowing that they hold enough information such as the QuestionID and so on.