I have field hobbies in table, which have; Reading,Sport,Paint
I want to checked back in gridview whichever hobbies's they have.
I insert in table used:
foreach (ListItem item in chkbxHobbies.Items)
{
if (item.Selected)
{
objBAL.HOBBIES += item + ",";
}
}
where chkGVHobbies is CheckBoxList control inside gridview.
i hope you already retrive particuler record in DataTable
CheckBoxList chkhbs = (CheckBoxList)GridView1.Rows[e.NewEditIndex].FindControl("chkGVHobbies");
string hbs = Convert.ToString(dt.Rows[0]["hobbies"]);
string[] str = hbs.Split(',');
foreach (string item in str)
{
foreach (ListItem gvchk in chkhbs.Items)
{
if (gvchk.Text==item)
{
gvchk.Selected = true;
}
}
Related
My datagrid in WPF app. displays csv file.I want to copy csv file to an array.Remove a string from array which is same as the selected row from datagrid (comparing indexes).In the end I display the string array in second datagrid.
//Storing csv file in string array
var filePath = "csvFile.csv";
using (StreamReader file = new StreamReader(filePath))
{
while (!file.EndOfStream)
{
int selectedIndex =int.Parse(dgData.SelectedIndex.ToString());
string strResult = file.ReadToEnd();
string[] result = strResult.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
List<string> list = new List<string>(result);
list.RemoveAt(selectedIndex);
foreach (string item in list)
{
Console.WriteLine(item);
Console.ReadLine();
}
dgtest.ItemsSource = list;
}
file.Close();
}
I would appreciate correcting my code.At the moment I have an error stating:
Index is out of range.
You are complicating things. Try something like this:
const string FilePath = "csvFile.csv";
List<string> lines = File.ReadAllLines(FilePath)?.ToList();
int selectedIndex = dgData.SelectedIndex;
if (lines != null && selectedIndex > 0 && lines.Count > selectedIndex)
lines.RemoveAt(selectedIndex);
dgtest.ItemsSource = lines;
Using Entity framework how can I pick any string to display in a textbox. Using myReader in the past I would do the following:
while (myReader.Read())
{
string sName = myReader.GetString(1);
txtName.Text = sName;
}
You have to load the entity (=table) you desire and than assign the property of the entity to the textbox.
Something like:
using (var myContext = new EntityContext())
{
myContext.TableName.Load(); //this will load all rows from the table
var list = myContext.TableName.Local; //.Local is a list of the entities which gets populated when you cann the Load() method
//now you can either enumarte your list like so
foreach (TableName item in list)
{
string sName = item.PropertyName; //PropertyName is the property you want to display, this would be like using not an index in myReader.GetString(1) but the columnname myReader.GetString("ColumnName")
txtName.Text = sName;
}
//or if you want to get a certain item out of your list you can use LINQ/MethodChains
//MethodChain
var item = list.First(x => x.PropertyName == "HelloWorld!");
string sName = item.PropertyName;
txtName.Text = sName;
//LINQ
var item = (from x in list
where x.PropertyName == "HelloWorld!"
select x).First();
string sName = item.PropertyName;
txtName.Text = sName;
//the methodchain and linq is a "new" technology that simplifies this code (which does the same)
TableName item = null;
foreach (TableName tempItem in list)
{
if (tempItem.PropertyName == "HelloWorld!")
{
item = tempItem;
break;
}
}
string sName = item.PropertyName;
txtName.Text = sName;
}
I have a WPF Application with two ComboBox
When I select the first one the items related to the first combobox will be populated on the second one
Here is my select Property
public string SelectedApplication
{
set
{
if (_selectedApplication == value) return;
this._selectedApplication = value;
InitializeTransactionTypes();
}
get
{
return this._selectedApplication;
}
}
here i am checking a matching id between the two comboboxes to populate the second combobox items.
ObservableCollection<TransactionTypeViewModel> _transTypeObsList = new ObservableCollection<TransactionTypeViewModel>();
private void InitializeTransactionTypes()
{
if (_selectedApplication != null)
{
var getAppCode =
ApplicationVModel.GetAllApplications()
.FirstOrDefault(apps => apps.Name == _selectedApplication);
var transTypeList = TransactionTypeVModel.GetAllViewModelTransTypes()
.Where(t => getAppCode != null && t.Id == getAppCode.Id);
transactionTypes = new ObservableCollection<TransactionTypeViewModel>(transTypeList);
NotifyPropertyChanged("TransactionTypes");
}
}
More information about methods:
List of VM mapped from List of Model
public List<TransactionTypeViewModel> GetAllViewModelTransTypes()
{
TransactionTypeViewModels = TransactionTypeModel.GetAllTransactionTypes().Select(transType => new TransactionTypeViewModel
{
Id = transType.Id,
Name = transType.Name,
})
.ToList();
return TransactionTypeViewModels;
}
Lets say I select first combobox has {A,B,C,D} ...and the second combobox has {A'1,A'2,A'3}, when I select item from first Combobox the second combobo keeps populating
items. I wanted to show only {A'1 for A} {B'1 for B} ...etc but now what it does is {A'1 A'1 A'1 ..... for A} {B'1 B'1 B'1 ....for B} for every select.
I want the previous selection to be cleared and display a new list per select. Thanks
To sum up comments. Instead of creating new ObservableCollection every time something changes reuse one that you already have and it will notify UI about changes. Your InitializeTransactionTypes should look something like this:
private void InitializeTransactionTypes()
{
if (_selectedApplication != null)
{
var getAppCode =
ApplicationVModel.GetAllApplications()
.FirstOrDefault(apps => apps.Name == _selectedApplication);
transactionTypes.Clear();
foreach(var transactionItem in TransactionTypeVModel.GetAllViewModelTransTypes().Where(t => getAppCode != null && t.Id == getAppCode.Id))
transactionTypes.Add(transactionItem);
}
}
and like this you should not have to notify about TransactionTypes changes any more
I have a datatable with data from file - it will be an ItemSource of my datagrid. And i am getting a datatable with the same schema from the database. I want to compare this two datatables and if there are some rows in the file that exist in the DB i need to check that the values of columns are equal. If not - I need to change the Background of the cell to red colour. May be it will be more clear from my code below:
dgrSimcards.ItemsSource = excelCards.Table.DefaultView;
var dbsource = new Tables.ExcelCards();
DBConnection.FillData(dbsource.Table);
if (!dbsource.HasRows) return;
foreach(DataRow impRow in import.Table.Rows)
{
var row = dbsource.Table.AsEnumerable().FirstOrDefault(p =>string.Compare( p[dbsource.card_numberColumn.ColumnName].ToString() ,impRow[dbsource.card_numberColumn.ColumnName].ToString())==0);
if (row != null)
{
if (string.Compare(row[import.comentsColumn].ToString(), impRow[import.comentsColumn].ToString()) != 0)
{
//here is merging problem - i need to change background colour
}
}
}
I found that it's possible to change cell's background via BindingProperty. But I don't know how to do that in my case. Yes, I'm really want to compare data on client-side. Any advices is appreciated.
I used an additional class:
public CardDoubleRow(DataRow mainRow, DataRow otherRow)
{
_mainRow = mainRow;
_otherRow = otherRow;
}
public object card_number
{
get { return _mainRow[ExcelSimCards.CardNumber]; }
}
public bool NumberEquals
{
get
{
return _otherRow != null
&& card_number.ToString().Equals(_otherRow[ExcelSimCards.CardNumber]
.ToString(),
StringComparison.OrdinalIgnoreCase);
}
}
foreach(DataRow impRow in import.Table.Rows)
{
var row = dbsource.Table.AsEnumerable().FirstOrDefault(p =>string.Compare( p[dbsource.card_numberColumn.ColumnName].ToString() ,impRow[dbsource.card_numberColumn.ColumnName].ToString())==0);
result.Add(new CardDoubleRow(impRow, row));
}
datagridcontrol.ItemsSource=result;
Then for each column i bound a special cellstyle with trigger like:
DataTrigger tg = new DataTrigger()
{
Binding = new Binding("NumberEquals"),
Value = false
};
We have WPF application, In which we use DataGrid on one form.
Now we want to calculate total of "AMOUNT" column of that datagrid on Winddow_Loaded event, So can it will display total of AMOUNT column in one TextBox
when Form get loaded. So how to iterate through all rows in DATAGRID & Calculate Total of "AMOUNT" column.
How to show this total in Footer of WPF Datagrid.?
Bind DataGrid to DataTable. After that you can just iterate through all rows:
double sum = 0;
foreach (var row in myTable)
{
sum += double.Parse(row["AMOUNT"].ToString());
}
myTextBox.Text = sum.ToString()
Function to convert DataGrid to DataSet:
namespace WpfApplication1
{
static class ExtClass
{
public static DataSet ToDataSet<T>(this IList<T> list)
{
Type elementType = typeof(T);
DataSet ds = new DataSet();
DataTable t = new DataTable();
ds.Tables.Add(t);
//add a column to table for each public property on T
foreach (var propInfo in elementType.GetProperties())
{
Type ColType = Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType;
t.Columns.Add(propInfo.Name, ColType);
}
//go through each property on T and add each value to the table
foreach (T item in list)
{
DataRow row = t.NewRow();
foreach (var propInfo in elementType.GetProperties())
{
row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value;
}
t.Rows.Add(row);
}
return ds;
}
}
}
EDIT: formatted spacing to make all code show-up in codeblock