cannot convert from 'System.Web.UI.WebControls.Label' to 'string'? - c#

I want to insert some values from grid to db while clicking button submit. While using the given below code shows an error. The code is given below. Help me to find a proper solution.
Code:
protected void btnApprove_Click(object sender, EventArgs e)
{
ShadingAnalysisDataSetTableAdapters.tbl_ItemRequest_StatusTableAdapter rs;
rs = new ShadingAnalysisDataSetTableAdapters.tbl_ItemRequest_StatusTableAdapter();
var ItemName = (Label)GridView2.SelectedRow.Cells[1].FindControl("lblItem");
var Quantity = (Label)GridView2.SelectedRow.Cells[2].FindControl("lblQnty");
rs.testInsert(ItemName, Quantity);
}
I have modified my code based on the above suggestions. But now I am getting another error. The new error is: Object reference not set to an instance of an object.

By doing this
var ItemName = (Label)GridView2.SelectedRow.Cells[1].FindControl("lblItem");
ItemName would be a Label instead of the text value of lblItem. I would guess that both parameters of rs.testInsert method are string so you got the error because you're passing two Labels instead of two strings. You can get the text value from the .Text property of the label as below
var ItemName = ((Label)GridView2.SelectedRow.Cells[1].FindControl("lblItem")).Text;
var Quantity = ((Label)GridView2.SelectedRow.Cells[2].FindControl("lblQnty")).Text;

You are finding Label control and assigning to var ItemName and var Quantity.So You are getting error "cannot convert from 'System.Web.UI.WebControls.Label' to 'string'".
var ItemName = (Label)GridView2.SelectedRow.Cells[1].FindControl("lblItem");
var Quantity = (Label)GridView2.SelectedRow.Cells[2].FindControl("lblQnty");
So, Add Text property to label.
var ItemName = ((Label)GridView2.SelectedRow.Cells[1].FindControl("lblItem")).Text;
var Quantity = ((Label)GridView2.SelectedRow.Cells[2].FindControl("lblQnty")).Text;

var ItemName = (Label)GridView2.SelectedRow.Cells[1].FindControl("lblItem");
here you will get the label control on the ItemName and you can get the label text value on string variable as given below.
string Text_Value= ItemName.text;

Related

How can I save the correct ValueMember of a ComboBox to the entities/db?

How can I save the correct ValueMember of a ComboBox to the entities/db?
My Winform has ComboBoxes that take Values from Entities of a Lookup Data tabel, as in the following code:
private void FillComboBoxes()
{
chargedToComboBox.Invalidate();
ModelCS ctx = new ModelCS();
var query1 = from a in ctx.LuDatas
where a.Category == "Charged To" && a.IsActive == true
select new { LuValueMember = a.LuValueMember,
LuDisplayMember = a.LuDisplayMember };
var chargedTo = query1.ToList();
chargedToComboBox.DataSource = chargedTo;
chargedToComboBox.DisplayMember = "LuDisplayMember";
chargedToComboBox.ValueMember = "LuValueMember";
string ch = chargedToComboBox.SelectedValue.ToString();
MessageBox.Show(ch); // variable ch shows the CORRECT
// ValueMember
chargedToTextBox.Text = ch; // variable ch show the UNDESIRABLE
// DisplayMember
this.Refresh();
}
On SaveChanges() I get the following error:
'System.Data.Entity.Validation.DbEntityValidationException' occurred in EntityFramework.dll
To find out what is happening, I added a TextBox to the form, and attempted to store in the what I thought was the ComboBox.ValueMember. To do this, I stored the the ComboBox.SelectedValue in a variable (ch) and and stored this variable in the TextBox.Text. What shows up in the TextBox.Text is the DisplayMember of the Combo, not the ValueMember.
To test why, I added a MessageBox to the code to see the vaslue of 'ch'; it shows the corresct value of the ValueMember.
How can it be that in the MessageBox 'ch' has one value and in the TextBox.Text it has another?
All I wanted was to extract a lookup list from the LuData entities, show the choices by name in the ComboBox and store the value by a code in the database.
Try this:
chargedToTextBox.Text = chargedToComboBox.SelectedItem.ToString();

WPF: Get column name from selected row

I am trying to get the Row's particular column from selected item in wpf from DataGrid.
Name of DataGrid is Datagrid_Newsale.
I am getting alert of whole row when it is selected, So i tried mapping its column.
Say if row is-
{ ID = 3, CustomerName = xyz, SaleDate = 05.08.2013 00:00:00, TotalAmount = 10 }
Then it's column CustomerName=xyz is to be shown in textbox.
Getting row-
var copyitem = Datagrid_NewSale.SelectedItem;
if (copyitem == null)
{
MessageBox.Show("Please select values from list");
}
if (copyitem != null)
{
MessageBox.Show(copyitem.ToString());
}
For getting customerName into text box i tried creating a new instance of model-
public class CustomerDetailes
{
public string CustomerName { get; set; }
}
And values from database from Customer Table-
public void viewcustomername()
{
List<CustomerDetailes> ilist = null;
ilist = (from order in db.Customer
select new CustomerDetailes
{
CustomerName= order.CustomerName
}).ToList();
txtCustumer.Text = ilist.ToString();
}
So giving it one more try-
CustomerDetailes copyitem = (CustomerDetailes)Datagrid_NewSale.SelectedItem;
if (copyitem == null)
{
MessageBox.Show("Please select values from list");
}
if (copyitem != null)
{
MessageBox.Show(copyitem.ToString());
}
txtCustomer.text=copyitem.CustomerName; //CustomerName into a textbox
But it is referencing null in copyitem.
How can I get particular column from the whole row.
You will have to bind the ItemsSource of DataGrid to CustomerDetails collection in order to get CustomDetails in SelectedItem.
Create property in your viewmodel (if using MVVM) or in code behind like
List<CustomerDetails> customerDetails = new List<CustomerDetails>();
List<CustomerDetails> MyCollection
{
get
{
return myList;
}
set
{
myList = value;
PropertyChanged(this, new PropertyChangedEventArgs("MyCollection"));
}
}
and in xaml just do.
<DataGrid ItemsSource="{Binding MyCollection}"/>
OR if you are directly filling the Items in the datagrid add instances of CustomerDetails like
dataGrid.Items.Add(new CustomerDetails(){Name = "abc"}, xyz propertis)
Thanks
If you can access the grid from your selection event then following should give your the column
((DataGrid)sender).CurrentCell.Column.Header
and use some mapping for the column name to the property of the object your want to show
I came up with this easy solution.
Mapped datatype of copyitem that was Anonymous in my case. In this case using Dynamic datatype solved my problem.
Due to my data was coming dynamically and then i was trying to map out particular column, so it was not really possible to do it statically because there is not data then.
Using Dynamic Datatype-
dynamic copyitem = dataGrid1.SelectedItem;
Accessing property-
int localId = copyitem.ID;
furthermore for customerName,TotalAmount i did the same.
Linq Query changes-
var query= (from order in db.Customer
where order.ID=localId
select order).ToList();
DataGrid_OpenSale.ItemsSource=query // returning data to another datagrid.
in VB ⠀⠀⠀
Private Sub SCUSTDataGrid_GotFocus(sender As Object, e As RoutedEventArgs) Handles SCUSTDataGrid.GotFocus
Dim og As DataGridCell = e.OriginalSource
Dim ccontent As TextBlock = og.Content
Dim dg As DataGrid
dg = e.Source
Dim selcol As String = dg.CurrentCell.Column.Header.ToString
MessageBox.Show(selcol.ToString + ccontent.Text + " got focus event")
End Sub

How do I bind a DataGridViewComboBoxColumn to a property/method of an object that returns a list?

I have a custom object with several properties, one of which returns a list. This is the code for the object:
public class SearchResult
{
private int eventId;
private String eventTitle;
private int startDate;
private List<String> tags;
// Properties
public int EventId { get { return this.eventId; } }
public String EventTitle { get { return this.eventTitle; } }
public int StartDate { get { return this.startDate; } }
public List<String> Tags { get { return this.tags; } }
public SearchResult(int eventId, String eventTitle, int startDate, List<String> tags)
{
// Constructor code
}
public List<String> GetTags()
{
return this.tags;
}
}
I also have a DataGridViewComboBoxColumn that I want to bind to the Tags property. Basically, each SearchResult object will be displayed in its own row, and I want the List<String> in the Tags property of each object to be displayed in a ComboBox cell in that row. This is the code I have so far for my DataGridView:
BindingList<SearchResult> results = new BindingList<SearchResult>();
results.Add(new SearchResult(1, "This is a title", 2012, new List<String> { "Tag1", "Tag with a long name1" }));
results.Add(new SearchResult(2, "The quick brown fox", 2012, new List<String> { "Stack", "Overflow" }));
results.Add(new SearchResult(3, "In this tutorial, you create a class that is the type for each object in the object collection. ", 2012, new List<String> { "NYSE", "FTSE" }));
results.Add(new SearchResult(4, "another long piece of title text", -999, new List<String> { "Rabbits", "Chickens" }));
MyDataGrid.AutoGenerateColumns = false;
MyDataGrid.AllowUserToAddRows = false;
MyDataGrid.AllowUserToDeleteRows = false;
MyDataGrid.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.None;
MyDataGrid.BackgroundColor = System.Drawing.SystemColors.Control;
MyDataGrid.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
MyDataGrid.RowHeadersWidthSizeMode = System.Windows.Forms.DataGridViewRowHeadersWidthSizeMode.AutoSizeToDisplayedHeaders;
MyDataGrid.AutoSizeRowsMode = System.Windows.Forms.DataGridViewAutoSizeRowsMode.DisplayedCells;
MyDataGrid.DefaultCellStyle.WrapMode = DataGridViewTriState.True;
DataGridViewTextBoxColumn eventIdColumn = new DataGridViewTextBoxColumn();
eventIdColumn.DataPropertyName = "EventId";
eventIdColumn.HeaderText = "Event ID";
eventIdColumn.ReadOnly = true;
eventIdColumn.Width = 84;
DataGridViewTextBoxColumn eventTitleColumn = new DataGridViewTextBoxColumn();
eventTitleColumn.DataPropertyName = "EventTitle";
eventTitleColumn.HeaderText = "Event Title";
eventTitleColumn.ReadOnly = true;
eventTitleColumn.Width = 368;
DataGridViewTextBoxColumn startDateColumn = new DataGridViewTextBoxColumn();
startDateColumn.DataPropertyName = "StartDate";
startDateColumn.HeaderText = "Start Date";
startDateColumn.ReadOnly = true;
startDateColumn.Width = 130;
//I think I need to insert the code for the tags column here, but I'm not sure
MyDataGrid.Columns.Add(eventIdColumn);
MyDataGrid.Columns.Add(eventTitleColumn);
MyDataGrid.Columns.Add(startDateColumn);
//MyDataGrid.Columns.Add(tagsColumn);
MyDataGrid.DataSource = results;
I derived this code from a tutorial I found online, and it works perfectly.
I've been trying to bind the Tags property of SearchResult to a DataGridViewComboBoxColumn, but I'm not sure how. I've been looking at this question, which provides this code:
column.DataPropertyName = "Foo";
column.DisplayMember = "SomeNameField";
column.ValueMember = "Bar"; // must do this, empty string causes it to be
// of type string, basically the display value
// probably a bug in .NET
column.DataSource = from foo in Foo select foo;
grid.DataSource = data;
The reason I'm having trouble is because of a few nuances of the linked question that I don't understand.
According to the documentation and the linked question, DisplayMember should be linked to the property that "contains a description of the instance", but since SearchResult objects are added dynamically and don't have any description associated with them, should I just leave it blank?
ValueMember is giving me similar problems, since I'm unsure what to put even after reading its documentation.
In the linked question, the accepted answer binds the entire datagrid at once using LINQ. Is that how I should be doing this? I'm not sure how to modify that code for my situation, but I thought it would be something along these lines.
:
tagsColumn.DataPropertyName = "Tags";
tagsColumn.DisplayMember = ""; // I'm unsure of what to put here
tagsColumn.ValueMember = ""; // Once again, I don't know what to set this to
I also presume I should have a line that sets the DataSource for the column, e.g.
tagsColumn.DataSource = <some LINQ query, perhaps?>
but I don't know because the only mostly relevant C# source I've been able to find is that question.
UPDATE:
I did find a second question that suggests code similar to this for data binding:
// reference the combobox column
DataGridViewComboBoxColumn cboBoxColumn = (DataGridViewComboBoxColumn)dataGridView1.Columns[0];
cboBoxColumn.DataSource = Choice.GetChoices();
cboBoxColumn.DisplayMember = "Name"; // the Name property in Choice class
cboBoxColumn.ValueMember = "Value"; // ditto for the Value property
Based on that, I a) added the GetTags() method to SearchResult and added this code into my DataGridView initialisation code:
DataGridViewComboBoxColumn tagsColumn = new DataGridViewComboBoxColumn();
tagsColumn.DataSource = SearchResult.GetTags(); // ERROR
tagsColumn.DisplayMember = ""; // Still not sure
tagsColumn.ValueMember = ""; // ??
However, Visual Studio gives me an error on the second line when I try to run this:
An object reference is required for the non-static field, method, or property 'SearchResult.GetTags()'
UPDATE 2:
I'm still searching around for this without success. I don't understand how with other properties (e.g. EventId) I can simply declare the data property name as EventId, and it will display in the table, but I cannot do this with ComboBox columns.
Since the objects are instantiated in a separate class and put in a list, it doesn't seem to make sense to me that I should have to loop through the entire array of objects (of which there may be several hundred) to bind the Tags property to the ComboBox column for each instance, when I don't need to loop through the list of SearchResult objects to bind other properties, e.g. EventId.
Why does this binding-properties-by-name only work for some properties and not others?
I don't quite understand why you want to use DataGridViewComboBoxColumn to display a list of elements. This column kind is designed to allow user to select one of many possibilities. It seams it is not your case because you don't have public string SelectedTag{get;set;} property to store it. As I understand your model you have many tags already selected for your SearchResult and you want to display them in grid.
As documentation states:
http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcomboboxcolumn.datasource
Getting or setting this [DataSource] property gets or sets the DataSource property of the object returned by the CellTemplate property. Setting this property also sets the DataSource property of every cell in the column and refreshes the column display. To override the specified value for individual cells, set the cell values after you set the column value.
DataGridViewComboBoxColumn simply does not have capability to bind items property to data source because it assumes that there is only one list of elements that is used as data source for all rows of data grid.
I also assume that you would set ReadOnly = true property for this column as you have for all other. If so it would prevent user form seeing list of tags because drop down list would never be displayed.
If you wand to display list of strings in read only mode I would suggest to flatten this list of tags to single string:
public string Tags { get { return string.Join(", ", tags); } }
and display it in text column.
For the error , i can suggest you to make an instance of the class and then call the method as its not static or you can make your method static.
Moreover As you needs the comboboxcolumn ,
DataGridViewComboBoxColumn tagsColumn = new DataGridViewComboBoxColumn();
tagsColumn.DataSource = SearchResult.GetTags(); // ERROR
tagsColumn.DisplayMember = ""; // Still not sure
tagsColumn.ValueMember = ""; // ??
Mostly we have dropdowns for objects like Country(id,name) so DisplayMember = name will be shown as text in dropdown while ValueMember = id will be used in the referencing tables in database.But this is not your case.
Here you have a list of strings to show in dropdown , so you don't need to set them.
As written here
If the DataSource property is set to a string array, then ValueMember
and DisplayMember do not need to be set because each string in the
array will be used for both value and display.

ASP .NET - Retrieve values from selected Listview control row?

My Listview control contains 4 columns and 30 rows.
I can retrieve the row number by using:
//get row of listview item
ListViewDataItem item1 = e.Item as ListViewDataItem;
int findMe = item1.DisplayIndex;
How do I then get values from one or all 4 columns?
I was trying:
this.lblReponseRoute.Text = item1.FindControl("routenameLabel").ID.ToString();
UPDATE1:
The final solution is:
//get row of listview item
ListViewDataItem item1 = e.Item as ListViewDataItem;
int findMe = item1.DisplayIndex;
//find label value
var routeLabel = (Label)ListView1.Items[findMe].FindControl("routenameLabel");
this.lblReponseRoute.Text = routeLabel.Text;
If routenameLabel is a server control, I believe you're going to have to cast it as such prior to accessing the properties:
var routeLabel = (Label)item1.FindControl("routenameLabel");
lblResponseRoute.Text = routeLabel.ID.ToString();
Do you get an error on the code you've posted?
Edit: Note that in your real code you'd want to test for null before casting to the Label.
var routeLabel = (Label)item1.FindControl("routenameLabel");
lblResponseRoute.Text = routeLabel.ID.ToString();
It should be:
var routeLabel = (Label)item1.FindControl("routenameLabel");
lblResponseRoute.Text = routeLabel.Text.ToString();
.Text not .ID, we already know the name of the label.

How can I get the Text value of a TextBox whose Name gets assigned at runtime?

I am creating a TextBox with the following code:
TextBox textBox = new TextBox();
textBox.Name = propertyName;
textBox.Text = value;
textBox.Width = FormControlColumnWidth;
textBox.SetResourceReference(Control.StyleProperty, "FormTextBoxStyle");
sp.Children.Add(textBox); //StackPanel
FormBase.Children.Add(sp);
On a button click, I want to get the text value of that text box, but I can't specify in code:
string firstName = FirstName.Text;
since "FirstName" will be defined at runtime. So how do I get the text value of the Textbox without knowing the name of the textbox at compile time?
The following is what I have so far but it says that it can't find "FirstName" even though it gets defined at runtime:
private void Button_Save(object sender, RoutedEventArgs e)
{
using (var db = Datasource.GetContext())
{
var item = (from i in db.Customers
where i.Id == TheId
select i).SingleOrDefault();
item.FirstName = ((TextBox)FindResource("FirstName")).Text;
db.SubmitChanges();
}
}
REPRODUCABLE EXAMPLE:
I posted a full reproducable example of this problem here: Why can't I access a TextBox by Name with FindName()?, perhaps easier to analyze.
The simplest solution would probably to keep a reference to your textbox somewhere in your code. Just add a
private TextBox _textbox
at the top of your class and set it to the TextBox you add in your code. Then you can refer to it in your Button_Save event handler.
You can retrieve it like this:
TextBox tb=(TextBox)Children.First(w=>w.Name=="FirstName");
Not sure what that sp in your code is, but if you really need the 2nd level of controls, you could run a foreach loop over the first level then search by name on the second level.
The answer to this question is you have to use this.RegisterName("FirstName", textBox); which is explained here: Why can't I access a TextBox by Name with FindName()?
You can find any element using FindName:
var c = (FrameworkElement)this.FindName("somename");
I can't write comments, so this is as a reply to your comment.
Why not use a
Dictionary<string, TextBox>
as a class property?
that way you can keep references to an indefinite number of textbox instances in the class AND access them easily by name in the dictionary?

Categories

Resources