Get original object from DataRow in GridView C# - c#

I try to display a collection (IEnumerable) of objects (generated via Linq to Sql). Therefore I bind the Gridviews DataSource property to the generated output of my Linq to SQL method. In the SelectedIndexChanged event of the GridView I try to convert the selected rows DataItem back to my original object but end up with a null value instead.
Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
RlDataContext dc = new RlDataContext();
this.dgvReports.DataSource = dc.GetReports(1);
this.dgvReports.DataBind();
}
protected void dgvReports_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.dgvReports.SelectedIndex >= 0)
{
Report rpt = (Report)this.dgvReports.SelectedRow.DataItem;
}
}
The return type of GetReports is ISingleResult<Report>

Use a bindingsource between your datagridview and your list. When a selection is made is datagridview use the bindingsource's Current property to get you the right item from the list.

This is how I always get my information from a datagridview
string variabel = yourDataGridView["Columnname"].ToString();
You can also use this in a loop then it will be:
string variabel = yourDataGridView["RowNumber"].Cells["Columnname"].Value.ToString();
I hope this helps!

Related

How to retrive a cell value from a ASPxGridView in an event?

I have a simple ASPxGridView which fires a OnCustomButtonCallback
I have tried the following code:
protected void grid_CustomButtonCallback(object sender, ASPxGridViewCustomButtonCallbackEventArgs e)
{
MyGridView.Rows[0].Cell[0].Value;
}
But it does not see Rows: ASPxGridView does not contain a definition of Rows
I am using DevExpress. Thank you in advance.
P.S. I'd like to get data from the row in which I clicked the custom button on
You can retrieve a particular column/field values using the ASPxGridView.GetRowValues method and pass the related row's VisibleIndex retrieved from the EventArgs e.VisibleIndex property as a parameter:
protected void grid_CustomButtonCallback(object sender, ASPxGridViewCustomButtonCallbackEventArgs e) {
var rowValues = grid.GetRowValues(e.VisibleIndex, "FIELD_NAME_HERE");
}

How to get asp.net dropdownlist to allow selections

I have a dropdownlist on a webform that I fill from a sql query, I then want to be able to select individual items in the dropdown and have corresponding fields from a datatable fill textboxes on the form
Problem is rowSel is returning 0 and the dropdown won't let me select any other item it always snaps back to the first itenm in the list.
Thought this might have something to do with autopostback being set to true, but if I set it to false that causes otheer problems, Not sure what else to try Im a winforms person and very new to asp.net
protected void ddClients_SelectedIndexChanged(object sender, EventArgs e)
{
int rowSel = ddClients.SelectedIndex;
txtClient.Text = dsShow.Rows[rowSel["ClientsTableFieldA"].ToString();
}
It should allow me to select a value from the drop down then populate some textboxes with fields from the datatable.
You could try:
protected void ddClients_SelectedIndexChanged(object sender, EventArgs e)
{
txtClient.Text = ddClients.SelectedItem.Value.ToString();
}
protected void ddClients_SelectedIndexChanged(object sender, EventArgs e)
{
txtClient.Text = ddClients.SelectedItem.Text;
}
As suggested by B. Seberle
DDL items have fields value and text so it depends how you bound the ddl to SQL datasource.
place break point on txtClient.Text = ddClients.SelectedItem.Text see if item list is empty.
it should not be necessary but you can force a ddClient.databind() in page_load if(!Page.IsPostback).
however ddClients_SelectedIndexChanged will only trigger on postback.

How to get dropdownlist selected value in Page_Init event c#

I tried below code in Page_Init() but i am getting null values. How to get Dropdownlist selected values in Page_Init().
protected void Page_Init(object sender, EventArgs e)
{
string test1 = Request.Form[ddlProjectResource.Text];
string test2 = Request.Form[ddlProjectResource.SelectedValue];
}
This will give you the SelectedValue of ddlProjectResource:
Request.Form[ddlProjectResource.UniqueID];
If you list is not populated from an external data-source then you should be able to use:
(DropDownList)page.FindControl(ddlProjectResource.UniqueID).SelectedItem;
Saying that the first solution is more performant as it only has to scan through the collection of values in the Form collection instead of scan through the whole html page.

Updating textbox based on datagrid view

I have this datagrid view which links to the table answers in the database. The user can edit answers to questions in this form, but I'd like for the textbox to be updated as the button moves onto next answer. This is so the user can edit/delete stuff in the textbox and save it.
private void NextQuestion_Click(object sender, EventArgs e)
{
QuestionsBindingSource.MoveNext();
}
How can I get the textbox to refresh based on selected record in datagridview?
Since you are using a BindingSource, you can get the Current object, cast it to it's type, and get a value.
Let's assume you are bound to a DataTable:
private void NextQuestion_Click(object sender, EventArgs e)
{
if (QuestionsBindingSource != null)
{
QuestionsBindingSource.MoveNext();
if (QuestionsBindingSource.Current != null)
{
DataRow row = (DataRow)QuestionBindingSource.Current;
yourTextBox.Text = row["FieldYouWant"].ToString();
}
}
}
What you cast Current to and the subsequent value reference are both dependent upon what you are bound to (what QuestionsBindingSource is). Adjust this example accordingly.

Object reference not set to an instance of an object in ComboBox

I've comboBox in windows forms which I've bound to datasource, which is correctly returning Id associated with particular name in combobox whenever form loads.
private void PurchaseMaster_Load(object sender, EventArgs e)
{
DataTable dt = productMasterBAL.GetTable("Select * from productMaster");
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "ProductName";
combBox1.ValueMember = "ProductId";
}
But whenever I select any value in Combobox I get:
NullReferenceException was unhandled. Object reference not set to an
instance of an object
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
DataRowView row = comboBox1.SelectedValue as DataRowView;
MessageBox.Show(String.Format("{0}", row["ProductId"])); //This line is causing exception
}
Could anyone please tell how can I solve this problem?
I think you should be checking combobox1.SelectedItem rather than SelectedValue.
DataRowView row = combobox1.SelectedItem as DataRowView;
SelectedItem is the databound row which created that entry in the combobox. SelectedValue will be the ProductID of that row.
Or, you could try
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string productId = combobox1.SelectedValue as string;
if (productId != null)
{
MessageBox.Show(productId);
}
}
You should be checking for the values like this
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox cmb = (ComboBox)sender;
MessageBox.Show(cmb.SelectedValue.ToString());// cmb.SelectedText
}
This should give you the selected Product Id in the combobox
The items in Combobox are stored as ObjectCollection and not exactly a DataRow or DataRowView as you seem to be expecting.
Have you debugged? Check that row isn't null? from msdn:
The as operator is like a cast operation. However, if the conversion
is not possible, as returns null instead of raising an exception.
Have you checked if this expression is valid as type?
May be row["ProductId"] is not a string field I think, so its returning an exception while formatting.
You are trying to cast PName.SelectedValue which is of type "String" to object DataRowView\ using 'safe-cast'. as returns null if object can't be cast to desired class. So, the actual mistake is in
DataRowView row = PName.SelectedValue as DataRowView;
Try direct cast with DataRowView row = (DataRowView)PName.SelectedValue, you'll definitely will get an error.
You should query your data source again to fetch data object.
Check out my generic solution on this thread:
c# loop through combobox where datasource is a datatable with text
Basically, you can call my function, telling it the type of each ComboBox Item, and it'll do the rest.
ComboBoxHelper.SetComboBoxSelectionByValue<EmployeeRecord>(comboBoxEmployees, someEmployeeID);
Hope this helps!

Categories