I want to retrieve data from database on the current logged in SharePoint user and show it on a control in a detailsview. But I really don't know how to achieve that on the best way. This is a code I've tried but it shows null.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
GetEmployeeCv();
}
}
private void GetEmployeeCv()
{
using (var db = new KnowItCvdbEntities())
{
SPWeb theSite = SPControl.GetContextWeb(Context);
SPUser theUser = theSite.CurrentUser;
string strUserName = theUser.LoginName;
var theEmpl =(from p in db.EMPLOYEES
where p.username == strUserName
select p).FirstOrDefault();
if(theEmpl != null)
{
Image empImg = (Image)DetailsViewShowFullCv.FindControl("imageProfPic");
empImg.ImageUrl = theEmpl.image;
}
}
}
If I want to databind my detailsview like:
Image empImg = (Image)DetailsViewShowFullCv.FindControl("imageProfPic");
empImg.ImageUrl = theEmpl.image;
DetailsViewShowFullCv.DataSource = ??;
DetailsViewShowFullCv.DataBind();
I don't really know how to do it. Anyone out there that can help me out?
a) The DataSource should be the variable which holds the data. In this case it would be theEmpl
b) Run this through the debugger to check if strUserName is what you expect. The LoginName field typically returns the domain and username like "DOMAIN\UserName" so there's a chance that it will return a null (null by default) value if you're only storing the UserName part in the database without the Domain\
c) For Databinding, either change your LINQ query to p.FieldNameToDatabind or know how to write the Databind code in asp markup so that you can actually display the field.
Related
I've a DropDownList - ASP.NET WebForm where it's filled up with roles and did it like the below from database:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
LoadDropDownBox();
}
}
public void LoadDropDownBox()
{
ddlUserRole.DataSource = aDbOperations.GetRoles(); //List of objects here
ddlUserRole.DataTextField = "roleName";
ddlUserRole.DataValueField = "roleId";
ddlUserRole.DataBind();
}
It works fine. Now my requirement is to get the selected role of a user when I edit or update user details. So say a user has role Admin, then while editing, the admin role should be selected by default along with other values in the DropDownList. So I tried something like this in the same default page:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
foreach (var item in aDbOperations.GetUserWithId(id)) //Passing query string here to match the id of the editing details
{
ddlUserRole.Value = item.roleName; //Get the selected role name by default while editing user details
}
LoadDropDownBox();
}
}
Even tried this:
ddlUserRole.SelectedItem.Value = item.roleName;
Though it didn't work and not getting the value selected by default along with other role values from database. Anything missed here?
Update - 1: Even tried the below one, but still not done
if (ddlUserRole.Items.FindByText(item.roleName.ToString()) != null)
{
ddlUserRole.Items.FindByText(item.roleName.ToString()).Selected = true;
}
Move your foreach after the LoadDropDownBox() function because the drop down has no loaded values before then.
Then if you know your dropdown contains the value FOR SURE then you can just do
ddlUserRole.SelectedValue = item.roleId.ToString();
Otherwise you would need to do a check to prevent an error like so:
ListItem selectedListItem = ddlUserRole.Items.FindByValue(item.roleId.ToString());
if (selectedListItem != null)
{
selectedListItem.Selected = true;
}
Your final code should look like this:
if(!IsPostBack)
{
LoadDropDownBox();
foreach (var item in aDbOperations.GetUserWithId(id)) //Passing query string here to match the id of the editing details
{
ListItem selectedListItem = ddlUserRole.Items.FindByValue(item.roleId.ToString());
if (selectedListItem != null)
{
selectedListItem.Selected = true;
}
}
}
I am working with WinForm in this i have 3 RadioButton one ComboBox and have three BindingSource
I want that when I check any of the RadioButtons, the values from the particular DataSources get bound to the ComboBox's ValueMember and DisplayMember.
The program has a SQL query where I want to send value based on the checked radio button.
private void rdbMed_CheckedChanged(object sender, EventArgs e)
{
cmbStock.DataSource = null;
cmbStock.DataSource = this.medicinesBindingSource;
this.cmbStock.DisplayMember = ""; //i want to bind "Med_ID" from medicinesBindingSource
this.cmbStock.ValueMember = ""; //"Med_Name"
}
private void rdbCat_CheckedChanged(object sender, EventArgs e)
{
cmbStock.DataSource = null;
cmbStock.DataSource = this.categoriesBindingSource;
this.cmbStock.DisplayMember = ""; //"category_Name"
this.cmbStock.ValueMember = ""; // category_ID"
}
private void rdbPharm_CheckedChanged(object sender, EventArgs e)
{
cmbStock.DataSource = null;
cmbStock.DataSource = this.pharmaceuticalBindingSource;
this.cmbStock.DisplayMember = "";// "Pharma_Name"
this.cmbStock.ValueMember = "";// "Pharma_ID"
}
Bellow are the parameter of the Query. It will help you to understand what I want to achieve.
if (rdbMed.Checked)
{
con.cmd.Parameters.AddWithValue("#Med_ID", cmbStock.ValueMember);
con.cmd.Parameters.AddWithValue("#category_ID", "");
con.cmd.Parameters.AddWithValue("#Pharma_ID", "");
}
else if (rdbCat.Checked)
{
con.cmd.Parameters.AddWithValue("#Med_ID", "");
con.cmd.Parameters.AddWithValue("#category_ID", cmbStock.ValueMember);
con.cmd.Parameters.AddWithValue("#Pharma_ID", "");
}
else if (rdbPharm.Checked)
{
con.cmd.Parameters.AddWithValue("#Med_ID", "");
con.cmd.Parameters.AddWithValue("#category_ID", "");
con.cmd.Parameters.AddWithValue("#Pharma_ID", cmbStock.ValueMember);
}
Easiest and the least pain way of doing this is resolving it inside SQL command and way to do it is cast your columns with AS VM and AS DM and make your DisplayMember = "DM" and ValueMember = "VM", so if you have sql query like SELECT USERID AS VM, NAME AS DM or SELECT PRODUCTID AS VM, NAME AS DM it will both work.
Problem later is if you do something with code and you may make mistakes trying to get USERID from databinding but it is instead VM. To avoid this you could "double select" values in query like SELECT USERID, NAME, ...., USERID AS VM, NAME AS DM this way you will have VM and DM for your controls but still hold original columns.
I encountered a problem whereby when the user clicked on the delete button, Nothing happens and when I insert breakpoint to check, The selectLocStation is null. Why is it happening? Can anyone kindly solve my doubts about it?
Here are the codes for you to see my Delete codes. Appreciate any helps that were offered.
private void btnDel_Click(object sender, EventArgs e)
{
using (satsEntities Setupctx = new satsEntities())
{
int selectLocStation = Convert.ToInt32(cbLocStation.SelectedValue);
var DeleteRTiming =
(from delLocStation in Setupctx.requiredtimings
where delLocStation.RequiredLocationStationID == selectLocStation
select delLocStation).SingleOrDefault();
if (DeleteRTiming != null)
{
Setupctx.DeleteObject(DeleteRTiming);
Setupctx.SaveChanges();
cbLocStation.SelectedIndex = -1;
this.Edit_TS_Load(null, EventArgs.Empty);
MessageBox.Show("Selected Required Timing And " +
"The Location Station Has Been Deleted.");
}
}
}
This is the codes that were used to bind.
private void Edit_TS_Load(object sender, EventArgs e)
{
using (satsEntities Setupctx = new satsEntities())
{
var DeleteRT = (from DelRT in Setupctx.requiredtimings
join locationstationname ls in Setupctx.locationstationnames on DelRT.RequiredLocationStationID equals ls.locationstationID
select ls.locStatname).Distinct().ToList();
foreach (var locstationData in DeleteRT)
{
cbLocStation.Items.Add(locstationData);
}
}
}
How can selectLocStation be null ? it is of type int, are you getting any exception or you mean your object DeleteRTiming is null ? probably its the DeleteRTiming which is null
The simple answer to that the record you are looking in the database against selectLocStation is not there.
You need to put a break point and see what is being held by 'selectLocStation` and then check the database manually if the record exists in the database.
when you bind your control, you must set it in ! IsPostback and persist you with ViewState
If(! IsPostBack)
{
BindYourControl(); //For just first load.
}
Persist with
EnableViewState = true;
In order to don't erase your selected value
If this is a silverlight application then you might want to use
cbLocStation.SelectedItem
Or it is a ASP.Net site and you rebind the data on every pageLoad
Either way you should have an exception because you are trying to convert a null value.
See the method that you have used to bind the combo box
cbLocStation.Items.Add(locstationData);
This will create the combobox with "ValueField" and "TextFiled" with value of the variable "locstationData"
So when you try to get selected value from cbLocStation.SelectedValue ,it will always contain name and so you cannot parse it to integer.
There is another overload for the "Add" Which will accept Value(Id) and Text(Text to display)
cbLocStation.Items.Add(new ListItem(locstationData.locStatname, locstationData.locStatID));
Try to change the binding portion like this
I have a dropdown in my webpage, which always returns the value 0 as the selected index no matter whichever item the user selects. I have populated the dropdown using a DB query. And I am populating in on Page_Load method in my page. The code shown below does the specified work: int danceid;
protected void Page_Load(Object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateDanceDropDown();
}
}
private void PopulateDanceDropDown()
{
DataTable dt = new DataTable();DataRow row = null;
dt.Columns.Add("Did", Type.GetType("System.Int32"));
dt.Columns.Add("DName", Type.GetType("System.String"));
var dancer_dance = (from dd in context.DANCER_AND_DANCE
where dd.UserId == dancerId
select new
{
Value = dd.DanceId,
Text = dd.DanceName
}).ToList();
foreach (var dndd in dancer_dance)
{
row = dt.NewRow();
row["Did"] = dndd.Value;
row["DName"] = dndd.Text;
dt.Rows.Add(row); dances.DataSource = dt;
dances.DataTextField = dt.Columns[1].ToString();
if (!IsPostBack)
{
dances.DataBind();
}
}
protected void changeIndex(object o, EventArgs e)
{
danceid = dances.SelectedIndex;
}
protected void dropthedance(object o, EventArgs e)
{
int danceIDFromDropDown = danceid;
var dancer_dance = from dd in context.DANCER_AND_DANCE
where dd.DanceId == danceIDFromDropDown
select dd;
foreach (var dndd in dancer_dance)
{
context.DANCER_AND_DANCE.DeleteOnSubmit(dndd);
}
try
{
context.SubmitChanges();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
The line int danceIDFromDropDown = danceid; in the method dropthedance always has the value 0. Pleaseeeeeeeeeeeeee help someone
Are you sure that you want to be using the index as the ID? Typically, you're going to want to set the actual ID from your database as the DataValueField and then you can grab the value that way.
But I also noticed that you grab the index and place it into a variable on the indexchanged event and then you try to use that value in a different method. I'm assuming that danceid is an attribute somewhere not shown here. At any rate, the value isn't persisting through postbacks. Instead of trying to store it in a variable like you would on a desktop application, try adding EnableViewState="True" to your dropdown control. Then get that index on your submit handler directly. Or if you really want to store it in a variable, then try persisting the value of that variable by storing it in the session or caching it, then pull from that cache/session variable when it comes time to actually use the value.
But again, it might be better practice to place the danceid in the listitem object itself. Just the though of basing IDs on item indexes makes me shudder, especially when you populating the list from a database, because what happens when you add a new item to that list in the library and then try to sort them by name... then your indices become useless.
Replace
int danceIDFromDropDown = danceid;
with
int danceIDFromDropDown = dances.SelectedIndex;
It may work.
I have a web form (Page1.aspx) in which I am passing an ID as query string to another page (Page2.aspx).
Now in this page I have EntityDataSource which binds to GridView. How should I populate this gridview with that ID?
Eg. If my ID is 1056, then in my DataGridView in Page2.aspx should populate elements of this ID.
This is the code:
protected void Page_Load(object sender, EventArgs e)
{
string getEntity = Request.QueryString["EntityID"];
int getIntEntity = Int32.Parse(getEntity);
if (getIntEntity != 0)
{
//What should I do here???
}
}
What should I do? Thank You!
See "Using a Control Parameter to Set the "Where" Property" in this tutorial:
http://www.asp.net/entity-framework/tutorials/the-entity-framework-and-aspnet-–-getting-started-part-3
The process will be similar except as "Parameter source" select QueryString instead of Control.
1.Take id from query string:
var strId = HttpContext.Current.Request.QueryString["ID"];
int id = 0;
int.TryParse(strId, out id);
if(id != 0)
{
...
}
2.Pass id to DataSource(mb this article help you) in Page_load event.