How to Add Data Contents to Data Grid in the Same Page without any Database Connectivity? - c#

Say, I have a TextBox - When the User enters contents into TextBox and Click on Add the Content Should Populate in the DataGrid Without any db connectivity. The User Can add repeated items in the TextBox and Click on Add, So Every Value gets Popluated in the Grid.
How do I achieve this?

You can try something like this, first you have to Imports the System.Collection.Generic namespace
private List<string> addContent(string content)
{
//create a generic list of string type
List<string> s = new List<string>();
for (int i = 0; i < 10; i++)
{
s.Add(content);
}
return s;
}
protected void btnAdd_Click(object sender, EventArgs e)
{
//Passed the List<> as DataSource and then bind the content in the list<> in the DataGrid
this.DataGrid1.DataSource = this.addContent(this.txtadd.Text);
this.DataGrid1.DataBind();
}
I Hope this works for you

Related

How to bind Access database to DataTable?

I'm new to C# and Visual Studio.
I'm working on a project that is searching through a database of information.
I want to bind a database (Microsoft access file) to my datagridview
but I want it to work with my preexisting code which utilizes a datatable converted into a dataview.
My database has a lot of information and I don't want to put it in manually. I've tried binding the information directly to the datagridview (through datasource in the properties) but then searching doesn't work**. I've looked into sql but im trying to avoid learning 2 languages at the same time.
My projects basic functionality contains: 1 combobox (idCbo) containing the search query's 1 datagridview for displaying the information
this setup is for searching one column only, im going to duplicate the code for the oher columns
The name of the column in the datagridview selects the column(id) for filtering then the combo box(idCbo) searches that column for matching characters in the datagridview and comboBox list.
the combo box contains the values 1-100 for searching the column
public partial class Form1 : Form
{
DataTable dt = new DataTable();
DataView dataView;
public Form1()
{
InitializeComponent();
dt.Columns.Add("id", typeof(int));
for (int i = 0; i < 100; i++)
dt.Rows.Add(i);
dataView = new DataView(dt);
this.dataGridView1.DataSource = dataView;
}
private void idCbo_SelectedIndexChanged(object sender, EventArgs e)
{
string query = idCbo.Text;
dataView.RowFilter = $"convert(id,'System.String') LIKE '%{query}%'";
}
}
**
Binding the database to the datagridview while using this code renders column titles but not the information and the code cannot access the database, columns or the rows System.Data.EvaluateException: 'Cannot find column ...
Big thanks to Johng for assisting me with the code :)
CURRENT WORKING CODE
public Form1()
{
InitializeComponent();
}
public static BindingSource gridBindingSource;
private void idCbo_SelectedIndexChanged(object sender, EventArgs e)
{
string query = idCbo.Text;
gridBindingSource = (BindingSource)dataGridView1.DataSource;
if (gridBindingSource != null)
{
if (query == "All")
{
gridBindingSource.Filter = "";
}
else
{
gridBindingSource.Filter = "convert(id,'System.String') LIKE '%" + query + "%'";
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the '_InfoFinalv_2___CopyDataSet.Info' table. You can move, or remove it, as needed.
infoTableAdapter.Fill(this._InfoFinalv_2___CopyDataSet.Info);
idCbo.Items.Add("All");
for (int i = 1; i < 100; i++)
{
idCbo.Items.Add(i);
}
idCbo.SelectedIndex = -1;
}
private void idReset_Click(object sender, EventArgs e)
{
idCbo.SelectedIndex = -1;
}
If you have set up the grids data source in the designer “correctly” then using the DataView as you want can be simplified by using the existing BindingSource that is usually created when you set up the grid’s data source in the designer.
We can use the existing grid’s BindingSource and then use it’s Filter property as opposed to converting the BindingSource to a DataView to filter. This will allow us to set the filter in the grid WITHOUT having to “change” the grids data source.
Remove all the code you have in the form constructor obviously leaving the InitializeComponent(); and add the code below to the forms Load event. In the load event all we do is set up the combo box with the proper values. I added an “All” option to allow the user to “un-filter” the data in the grid.
private void Form1_Load(object sender, EventArgs e) {
// TODO: This line of code loads data into the 'database1DataSet.EmployeeDT' table. You can move, or remove it, as needed.
employeeDTTableAdapter.Fill(this.database1DataSet.EmployeeDT); // <- created by the designer
idCbo.Items.Add("All");
for (int i = 1; i < 100; i++) {
idCbo.Items.Add(i);
}
idCbo.SelectedIndex = 0;
}
Then in the combo boxes SelectedIndexChanged event... change the code as shown below. Cast the grids DataSource to a BindingSource and then use its Filter property.
private void idCbo_SelectedIndexChanged(object sender, EventArgs e) {
string query = idCbo.Text;
BindingSource GridBS = (BindingSource)dataGridView1.DataSource;
if (GridBS != null) {
if (query == "All") {
GridBS.Filter = "";
}
else {
GridBS.Filter = "EmpID LIKE '%" + query + "%'";
}
}
}
Here's the tip:
On the form load, make an ajax call to the database and fetch only the required data columns. Return data will be in JSON that can be used as data for DataTable.
I used it in an MVC project recently and it works fine. If you would like I can share the detailed code and logic.
Not sharing the code since I'm not sure if you are on .Net MVC.

How to dynamically filter DataGridView using TextBox data?

I created a simple DataGridViewa with a single column and added a TextBox above.
Currently the text actually a DataTable (I though this would make things easier for filtering) with 2 columns, number and text (I hide the number in the DataGridView ). I can change it to any other class if required.
When the user enters a letter in the TextBox, I want to dynamically filter and show only the lines containing this text.
I load the data to the DataGridView like this:
private void PhrasesForm_Load(object sender, EventArgs e)
{
phrasesDataGridView.ReadOnly = true;
phrasesDataGridView.DataSource = _phrases.Phrases;
phrasesDataGridView.Columns[0].Visible = false;
this.phrasesDataGridView.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
When add another letter the filter will be readjusted.
What do I write here...
private void filterBox_TextChanged(object sender, EventArgs e)
{
}
If you have a DataGridView, or any Control with a DataSource, consider using Nuget Package BindingListView. It has functionality to sort the binding list by any column on a mouse click, but it also has functionality to filter the data.
List<Customer> customers = ...
BindingListView<Customer> customerView = new BindingListView<Customer>(customers);
dataGridView1.DataSource = customerView;
And presto, if shows all Customers. The columns depend on you column definition.
To filter the customers, for instance, show only customers with born before a certain date:
void ShowCustomers(DateTime limitDate)
{
customerView.ApplyFilter( customer => customer.BirthDay < limitDate));
}
Result: only the older Customers are shown.
You can do it similarly:
void ShowItemsWithPhraseStart(string phraseStart)
{
myView.ApplyFilter(row => row.Phrase.StartsWith(phraseStart));
}
And bingo: the datagrid shows only the row with a value for property Phrase that starts with phraseStart.
private void OnTextBocChanged(object sender, ...)
{
var text = this.TextBox1.Text;
ShowItemsWithPhraseStart(text);
}

Title of DropDownList's items is not shown in Chrome v.43

After a long time searching for this problem I've decided to try my luck here... I'm trying to add a tooltip (title) for the items in a Drop Down List.The title is showed in IE and Firefox browsers. The DDL is creating dynamically and the DDL's DataSource is a list called "labCourses" .This is my code:
protected void Page_Load(object sender, EventArgs e)
{
ExpScheduleClass ExpSC = new ExpScheduleClass();
List<string> labCourses = ExpSC.getCourseList();
// dynamically create a dropdown list (aka DDL)
DDLCourses = new DropDownList();
DDLCourses.DataSource = labCourses; // set the data source
DDLCourses.DataBind(); // bind the data to the DDL control
BindTooltip(DDLCourses);
DDLCourses.AutoPostBack = true;
DDLCourses.SelectedIndexChanged += DDLCourses_SelectedIndexChanged;
coursePH.Controls.Add(DDLCourses);
}
public void BindTooltip(ListControl lc)
{
for (int i = 0; i < lc.Items.Count; i++)
{
lc.Items[i].Attributes.Add("title", lc.Items[i].Text);
}
}
I looked at the option element with the web inspector and the title was there (in the html), but is does not shown when the mouse was over the option.
In other browsers the title is shown on mouse hover. What may be the cause for this? Thank you very much...

C# 2 Comboboxes with identical, not twice-selectable content

I have a dialog form where the user has to selected which colums from a textfile he wants to use for drawing a graph.
If someone doesn't quite understand what I mean, please look at the following example:
The dialog opens
The user selects e.g. that the x-values of his graph shall be from the second column of the textfile
The user selects e.g. that the y-values of his graph shall be from the third column of the textfile
The user clicks "OK"
The problem I have is the following:
I want to prevent the user from selecting the same column for x and y values, which would result in a line in an angle of probably 45 degrees and make the graph useless.
Both comboboxes are filled with the same array of strings, which contains the headlines of the columns in the textfile. Getting those strings into the comboboxes works great, but:
I tried removing the item selected in one combobox from the other combobox and otherwise.
Before that, the currently selected item is stored in a variable and the items are reset to the default state, which means all headlines from the textfile.
But, as I programmatically set the index to where it was before, so that the user doesn't have to, the SelectedIndexChanged event fires and traps my code in an infinite loop.
public void setComboboxText()
{
cbX.Items.Clear();
cbY.Items.Clear();
cbX.Items.AddRange(cbText);
cbY.Items.AddRange(cbText);
}
void CbXSelectedIndexChanged(object sender, EventArgs e)
{
var item = cbX.SelectedItem;
setComboboxText();
cbX.SelectedItem = item;
cbY.Items.Remove(cbX.SelectedItem);
}
void CbYSelectedIndexChanged(object sender, EventArgs e)
{
var item = cbY.SelectedItem;
setComboboxText();
cbY.SelectedItem = item;
cbX.Items.Remove(cbY.SelectedItem);
}
The code does the following:
The currently selected item is temporarily stored
The items of the combobox are reset
The currently selected item is set to be the item stores before
The item selected in the changed box disappears from the other combobox
Any help appreciated, especially if someone could tell me if I can do what I want with another event or even without events.
Thanks in advance
I think this is what you are trying to achieve.
public partial class Form1 : Form
{
List<string> source1 = new List<string>();
List<string> source2 = new List<string>();
public Form1()
{
InitializeComponent();
for (int i = 0; i < 10; i++)
{
source1.Add("item" + i);
source2.Add("item" + i);
}
comboBox1.Items.AddRange(source1.ToArray());
comboBox2.Items.AddRange(source2.ToArray());
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox2.Items.Contains(comboBox1.SelectedItem))
{
comboBox2.Items.Clear();
List<string> updatedList = new List<string>();
updatedList = (from x in source2
where !x.Equals(comboBox1.SelectedItem)
select x).ToList<string>();
comboBox2.Items.AddRange(updatedList.ToArray());
}
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.Items.Contains(comboBox2.SelectedItem))
{
comboBox1.Items.Clear();
List<string> updatedList = new List<string>();
updatedList = (from x in source1
where !x.Equals(comboBox2.SelectedItem)
select x).ToList<string>();
comboBox1.Items.AddRange(updatedList.ToArray());
}
}
}
Make the source collections available avaiable to each combobox SelectedIndexChanged handlers
On each selection change update the source of the other combobox only if the newly selected item exists in the other combobox Items.

C# Textbox with databinding is not updating

I have a classic Form with 3 textboxes and 1 combobox. Combobox shows list of Users and 3 textboxes should contain details about the selected user in the combobox. For selected user I have a special attribute (as shown below) which I am using as data source. This is ok only on the first run. When the form is shown, changing user in combobox has no effect.
public partial class UserAdministration : Form
{
private readonly DataManager _dataManager = DataManager.Instance;
private User _selectedUser;
public UserAdministration()
{
InitializeComponent();
}
private void UserAdministration_Load(object sender, EventArgs e)
{
AddUsers();
textBoxName.DataBindings.Add("Text", _selectedUser, "Name");
textBoxSurname.DataBindings.Add("Text", _selectedUser, "Surname");
textBoxPassword.DataBindings.Add("Text", _selectedUser, "Password");
}
private void AddUsers()
{
var users = _dataManager.UserProvider.GetAll().Select(pair => pair.Value).ToList();
comboBoxUsers.DataSource = new BindingSource { DataSource = users };
comboBoxUsers.DisplayMember = "ListViewText";
if (users.Count > 0)
comboBoxUsers.SelectedIndex = 0;
}
private void comboBoxUsers_SelectedIndexChanged(object sender, EventArgs e)
{
_selectedUser = comboBoxUsers.SelectedItem as User;
}
}
What am I missing? What is wrong with data binding?
to bind your datasource to cb use this code:
comboBoxUsers.DataSource = users (directly to you datasource);
to bind the same data to textbox do it like this:
textbox1.DataBindings.Add("Text", users, "username", true);
the only point is, that you need to link both controls to the same ds instance
I have a form with ONLY a textbox that I wanted to bind to database column.
When I used the 'properties' settings to data-bind that textbox to one column, it created the bindingSource1 and table adapter for me.
When I clicked the SAVE button, I simply added bindingSource1.EndEdit(); and then it saved correctly to the database.

Categories