I created a table in dataset that is not in a database, I need to set data to this table and bind data to a combobox, how can I do this?
DataRowView drv = statusBindingSource.AddNew() as DataRowView;
drv.Row["Value"] = 1;
drv.Row["Name"] = "Active";
statusBindingSource.EndEdit();
statusBindingSource.Add(drv);
I cannot add external objects to this list.
The new DataTable is created, filled with data and bound to the combo box. I did not include a DataSet or BindingSource.
private void Form1_Load(object sender, EventArgs e)
{
CreateDataTable();
cbo1.SelectedIndex = -1;
}
private void CreateDataTable()
{
//Create new DataTable
DataTable dt = new DataTable();
//Add colums with column name and datatype
dt.Columns.Add("Value", Type.GetType("System.Int32"));
dt.Columns.Add("Name", Type.GetType("System.String"));
//Add data
object[] data = { 1, "Active" };
dt.Rows.Add(data);
object[] data2 = { 2, "Passive" };
dt.Rows.Add(data2);
//Bind to combo box
cbo1.DataSource = dt;
cbo1.DisplayMember = "Name";
cbo1.ValueMember = "Value";
}
private void Cbo1_SelectionChangeCommitted(object sender, EventArgs e)
{
MessageBox.Show($"The display member is {((DataRowView)cbo1.SelectedItem)["Name"]}, The value member is {cbo1.SelectedValue}");
}
Related
I want to bind gridview column from textbox value for example: I have two textbox and a button what i exactly want that i will give input in the two textboxes and when i clicked the button the textbox values will show in gridviw and want to do this for multiple times without replacing the previous values.
I found so many relevant answer but all are done with hard code inside button click event
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[2] { new DataColumn("Name",
typeof(string)),
new DataColumn("Age", typeof(decimal)) });
dt.Rows.Add(TextBox1.Text, TextBox2.Text);
GridView1.DataSource = dt;
GridView1.DataBind()
}
which replace the previous values when i insert new values, but i want to keep all the previous values in which I stuck .thanks
this code will help you to get current data from gridview to datatable
and then you can append new rows accordingly .
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt =GetGridData();
dr = dt.NewRow();
dt.Rows.Add(TextBox1.Text, TextBox2.Text);
GridView1.DataSource = dt;
GridView1.DataBind();
}
private DataTable GetGridData ()
{
DataTable _datatable = new DataTable();
for (int i = 0; i < grdReport.Columns.Count; i++)
{
_datatable.Columns.Add(grdReport.Columns[i].ToString());
}
foreach (GridViewRow row in grdReport.Rows)
{
DataRow dr = _datatable.NewRow();
for (int j = 0; j < grdReport.Columns.Count; j++)
{
if (!row.Cells[j].Text.Equals(" "))
dr[grdReport.Columns[j].ToString()] = row.Cells[j].Text;
}
_datatable.Rows.Add(dr);
}
return _dataTable;
}
You can store the values from each PostBack into a Session or ViewState, otherwise you'll lose all the data when the button is clicked again.
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt;
//check if the datatable already exists in the viewstate, if not create a new datatable
if (ViewState["myTable"] == null)
{
dt = new DataTable();
dt.Columns.AddRange(new DataColumn[2] { new DataColumn("Name", typeof(string)), new DataColumn("Age", typeof(decimal)) });
}
else
{
//correct viewstate exists, cast back to a datatable
dt = ViewState["myTable"] as DataTable;
}
//add the new values
dt.Rows.Add(TextBox1.Text, Convert.ToDecimal(TextBox2.Text));
//bind the datatable to the gridview
GridView1.DataSource = dt;
GridView1.DataBind();
//save the datatable into the viewstate
ViewState["myTable"] = dt;
//clear the textboxes
TextBox1.Text = "";
TextBox2.Text = "";
}
I have 2 listboxes in a window form, one on left and one on right. The
1st listbox have some items while the 2nd listbox is empty. Also there
are 2 buttons between the 2 listboxes which used to move item from/to
the 1st and 2nd listbox
My problem here is that after I bind the data to the 1st listbox (from
a database, using DisplayMember and ValueMember) , and I try to move 1
of the item from this 1st listbox to the 2nd listbox and I want that
the selected item is also removed from the 1st listbox by:
private void btnMoveRight_Click(object sender, EventArgs e)
{
ADD();
}
private void ADD()
{
int c = listJobBox.Items.Count - 1;
` for(int i= c; i>=0; i--)
{
if(listJobBox.GetSelected(i))
{
lstAssignedJobs.Items.Add(listJobBox.Items[i]);
listJobBox.Items.Remove(listJobBox.SelectedItem); ---error line
But the selected item is not removed from the 1st listbox.
it displays error message "Items collection cannot be modified
when the DataSource property is set."
can any one give me the solution to my problem.
Add a boolean column to your DataTable object, something like IsSelected.
Then instead of binding your listbox1 directly to the table, bind it to a BindingSource. Add 2 bindingsources to your form using the designer. And place this code in your code behind file.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.InitializeDataObjects();
}
private void InitializeDataObjects()
{
this.InitData();
this.InitBindingSources();
}
private void InitData()
{
ds = new DataSet();
var dt = new DataTable("Table1");
dt.Columns.Add("Name", typeof(string));
ds.Tables.Add(dt);
}
private void InitBindingSources()
{
bindingSource1 = new BindingSource();
bindingSource2 = new BindingSource();
bindingSource1.DataSource = ds;
bindingSource1.DataMember = "Table1";
bindingSource2.DataSource = ds;
bindingSource2.DataMember = "Table1";
listBox1.DataSource = bindingSource1;
listBox1.DisplayMember = "Name";
listBox2.DataSource = bindingSource2;
listBox2.DisplayMember = "Name";
}
}
Then when you load your data, do the following:
private void btnLoadAndBind_Click(object sender, EventArgs e)
{
this.FetchData(this.ds.Tables["Table1"]);
this.AddSelectedColumn(this.ds.Tables["Table1"]);
this.bindingSource1.Filter = "IsSelected = false";
this.bindingSource2.Filter = "IsSelected = true";
}
private void FetchData(DataTable dataTable)
{
string CS = "your connectionstring";
using (SqlConnection con = new SqlConnection(CS))
{
try
{
SqlDataAdapter da = new SqlDataAdapter();
con.Open();
var sqlcmd = new SqlCommand("SELECT Name FROM sometable", con);
sqlcmd.CommandType = CommandType.Text;
da.SelectCommand = sqlcmd;
da.Fill(dataTable);
}
catch (Exception ex)
{
MessageBox.Show("exception raised");
throw ex;
}
}
}
private void AddSelectedColumn(DataTable suppliersDataTable)
{
var dc = new DataColumn("IsSelected", typeof(bool));
suppliersDataTable.Columns.Add(dc);
foreach (DataRow dr in suppliersDataTable.Rows)
{
dr["IsSelected"] = false;
}
}
Now your listboxes are both connected to the same datatable and filtered based on the IsSelected property / column. Just set this column to true or false and it will flip from box to box. Your eventhandler of a button could look like this:
public void button_Click(object sender, EventArgs e)
{
if (this.bindingSource1.Current!= null)
{
var dr = ((DataRowView)this.bindingSource1.Current).Row;
dr["IsSelected"] = true;
}
}
This works!
Things will be become much simpeler if you use a typed dataset. Most of the bindings then can be done in the designer and your code behind will shrink to 20 lines of code....
Lets say listbox1 is bound to datatable1 (it could be any other collection type) and listbox2 is bound to datatable2. When you click on move button, remove the selected item from the collection i.e datatable1 and add that item to other collection i.e. datatable2 and re-bind the listbox1 and lisbox2.
Here is a rough working example:
public partial class Form1 : Form
{
private DataTable _dataSource1;
private DataTable _dataSource2;
public Form1()
{
InitializeComponent();
_dataSource1 = GetData1();
_dataSource2 = GetData2();
Initialize();
}
private void btnMove_Click(object sender, EventArgs e)
{
MoveItem();
}
void Initialize()
{
listBox1.DataSource = _dataSource1;
listBox1.DisplayMember = "Fruits";
listBox1.ValueMember = "Fruits";
listBox2.DataSource = _dataSource2;
listBox2.DisplayMember = "Fruits";
listBox2.ValueMember = "Fruits";
}
DataTable GetData1()
{
var dt = new DataTable();
dt.Columns.Add("Fruits");
dt.Rows.Add(new object[] {"Apple"});
dt.Rows.Add(new object[] { "Orange" });
dt.Rows.Add(new object[] { "Grapes" });
return dt;
}
DataTable GetData2()
{
var dt = new DataTable();
dt.Columns.Add("Fruits");
return dt;
}
void MoveItem()
{
var index = listBox1.SelectedIndex;
var dataRowToRemove = _dataSource1.Rows[index];
var listItem = dataRowToRemove[0] as string;
_dataSource1.Rows.Remove(dataRowToRemove);
var dataRowToAdd = _dataSource2.NewRow();
dataRowToAdd[0] = listItem;
_dataSource2.Rows.Add(dataRowToAdd);
Initialize();
}
}
I am using Visual C# 2008 to make a application that takes the data from textboxes and displays it in datagridview in another form the conforming make it entered to the database.
I send the data using dataTable with a function entered the data without any symentic error but when I call the other for the datagridview comes empty and the database comes empty. When I duplicate a primary key it gives an error stating "cannot duplicate primary key".
This is the code for the function that transfers that datatable
public DataTable showout() {
DataTable dtab = new DataTable();
DataColumn dc1 = new DataColumn("رقم المتسلسل");
DataColumn dc2 = new DataColumn("رقم الحساب");
DataColumn dc3 = new DataColumn("أسم الحساب");
dtab.Columns.Add(dc1);
dtab.Columns.Add(dc2);
dtab.Columns.Add(dc3);
// Create an array for the values.
object[] newRow = new object[3];
// Set the values of the array.
string s = numb.Text;
newRow[0] =numb.Text;
newRow[1] = textBox5.Text;
newRow[2] =note.Text;
DataRow row;
dtab.BeginLoadData();
// Add the new row to the rows collection.
row = dtab.LoadDataRow(newRow, true);
return dtab;
}
this is the code that I call the function in the other From
private void Cashagree_Load(object sender, EventArgs e) {
dataGridView1.DataSource = ch.showout();
}
the second datagrid entering function its in the same class
private void button1_Click(object sender, EventArgs e)
{
dataGridView1.Visible = true;
dataGridView1.DataSource = showout();
entering(true);
}
and this is the entering to the database
public void entering(bool bl)
{try{
if (bl)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
DateTime Date = DateTime.Today;
SqlCommand cmd = new SqlCommand("INSERT INTO Accont(Account_ID,Account_Name,Owners,Curency,Curncytype,Depet,Credet_devet,Date,Note) VALUES (#AccountID, #AccountName, #Owner, #Curncy,#Curncytype,#Depet,#Cridetdevet,#Date,#Note)");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#AccountID",numb.Text);
cmd.Parameters.AddWithValue("#AccountName", comboBox1.SelectedText.ToString());
cmd.Parameters.AddWithValue("#Owner", owner.Text);
cmd.Parameters.AddWithValue("#Curncy", curency.Text);
cmd.Parameters.AddWithValue("#Curncytype", curncyval.Text);
cmd.Parameters.AddWithValue("#Depet", Depet.Text);
cmd.Parameters.AddWithValue("#Cridetdevet", textBox5.Text);
cmd.Parameters.AddWithValue("#Date", Date);
cmd.Parameters.AddWithValue("#Note", note.Text);
connection.Open();//Owner
cmd.ExecuteNonQuery();}}
}
catch(Exception ee)
{MessageBox.Show(ee.Message);}
the conforming from the another form
private void button1_Click_1(object sender, EventArgs e)
{
ch.entering(true);
Close();
}
Instead of using the dtab.LoadDataRow, you should be using the dtab.Rows.Add(datarow) method.
An example of how to do this:
public DataTable showout()
{
DataTable dtab = new DataTable();
// More efficient way of adding the columns with types:
dtab.Columns.Add("رقم المتسلسل", typeof(String));
dtab.Columns.Add("رقم الحساب", typeof(String));
dtab.Columns.Add("أسم الحساب", typeof(String));
/*
DataColumn dc1 = new DataColumn("رقم المتسلسل");
DataColumn dc2 = new DataColumn("رقم الحساب");
DataColumn dc3 = new DataColumn("أسم الحساب");
dtab.Columns.Add(dc1);
dtab.Columns.Add(dc2);
dtab.Columns.Add(dc3);
*/
// Create a new row using the .NewRow method
DataRow datRow = dtab.NewRow();
datRow["رقم المتسلسل"] = numb.Text;
datRow["رقم الحساب"] = textBox5.Text;
datRow["أسم الحساب"] = note.Text;
// Add the new row to the DataTable
dtab.Rows.Add(datRow);
return dtab;
}
Reference:
How to: Add Rows to a DataTable
Adding Data to a DataTable
In solve it by the sending the DataTable dt from the first Form cash to the second Form cashagree as a prameter by calling the method that return datagridview
in cash form I wrote this:
cashagree gc2 = cashagree(showout());
in cashagree form I wrote this
DataTable dt = new DstsTsble();
public cashagree(DataTable d2){
dt =d2;
}
and in the load of `cashagree_Load` I asign the datagridview datasoure
private void Cashagree_Load(object sender, EventArgs e)
{
if (dt.Rows[0].IsNull(dt.Columns[0]))
{
MessageBox.Show("There no primary key");
Close();
}
dataGridView1.DataSource = dt;
dataGridView1.Columns[7].Visible = false;// Iwantn't all the datatable so I diapple some Columns
dataGridView1.Columns[5].Visible = false;
dataGridView1.Columns[7].Visible = false;
dataGridView1.Columns[6].Visible = false;
dataGridView1.Columns[4].Visible = false;
}
When adding items to a gridview, I want the user to be able to select and edit/remove the item before writing the file (from the gridview entries) to a csv format. When I click on "edit" and update the information, I get an error. There is no row at position 0. (or whatever row you select to edit). Here is my code.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SetFocus(parttxtbox);
table = new DataTable();
MakeDataTable();
}
else
table = (DataTable)ViewState["table"];
ViewState["table"] = table;
}
protected void MakeDataTable()
{
table.Columns.Add("Part", typeof(string));
table.Columns.Add("Quantity", typeof(Int32));
table.Columns.Add("Ship-To", typeof(string));
table.Columns.Add("Requested Date", typeof(string));
table.Columns.Add("Shipping Method", typeof(string));
//Persist the table in the Session object.
Session["table"] = table;
//Bind data to the GridView control.
BindData();
}
protected void addbtn_Click(object sender, EventArgs e)
{
part = parttxtbox.Text.ToUpper();
shipto = shiptotxtbox.Text;
reqdate = reqdatecal.SelectedDate.ToShortDateString();
shipmthd = shipddl.SelectedItem.ToString();
CreateTable();
}
public void CreateTable()
{
DataRow row = table.NewRow();
row["Part"] = part;
row["Quantity"] = qty;
row["Ship-To"] = shipto;
row["Requested Date"] = reqdate;
row["Shipping Method"] = shipmthd;
table.Rows.Add(row);
griditems.DataSource = table.DefaultView;
griditems.DataBind();
}
private void BindData()
{
griditems.DataSource = table;
griditems.DataBind();
}
protected void griditems_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//Retrieve the table from the session object.
DataTable dt = (DataTable)Session["table"];
//Update the values.
GridViewRow row = griditems.Rows[e.RowIndex];
dt.Rows[row.DataItemIndex]["Part"] = ((TextBox)(row.Cells[1].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["Quantity"] = ((TextBox)(row.Cells[2].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["Ship-To"] = ((TextBox)(row.Cells[3].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["Requested Date"] = ((TextBox)(row.Cells[4].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["Shipping Method"] = ((DropDownList)(row.Cells[5].Controls[0])).SelectedItem.ToString();
//Reset the edit index.
griditems.EditIndex = -1;
//Bind data to the GridView control.
BindData();
////Somewhat works, doesn't update the part field with the text entered
//TextBox partedit = (TextBox)griditems.Rows[e.RowIndex].FindControl("Part");
//DataRow row = table.NewRow();
//row["Part"] = partedit;
//row["Quantity"] = qty;
//row["Ship-To"] = shipto;
//row["Requested Date"] = reqdate;
//row["Shipping Method"] = shipmthd;
//table.Rows.Add(row);
}
The commented out part that says "Somewhat works" will write blanks in the field updated when you click update.
The time you are adding data table in Session there is no row in it, thats why you get error "There is no row at position 0."
You are assigning table from viewstate to table it would be session.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SetFocus(parttxtbox);
table = new DataTable();
MakeDataTable();
}
else
if(Session["table"] != null)
table = (DataTable)ViewState["table"];
}
protected void MakeDataTable()
{
table.Columns.Add("Part", typeof(string));
table.Columns.Add("Quantity", typeof(Int32));
table.Columns.Add("Ship-To", typeof(string));
table.Columns.Add("Requested Date", typeof(string));
table.Columns.Add("Shipping Method", typeof(string));
//Persist the table in the Session object.
Session["table"] = table; //This adds table without any record in it.
//Bind data to the GridView control.
BindData();
}
Add data table to session after you add records in datatable.
protected void addbtn_Click(object sender, EventArgs e)
{
part = parttxtbox.Text.ToUpper();
shipto = shiptotxtbox.Text;
reqdate = reqdatecal.SelectedDate.ToShortDateString();
shipmthd = shipddl.SelectedItem.ToString();
CreateTable();
Session["table"] = table;
}
Update the Session["table"] in griditems_RowUpdating after updating.
protected void griditems_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//Retrieve the table from the session object.
DataTable dt = (DataTable)Session["table"];
//Update the values.
GridViewRow row = griditems.Rows[e.RowIndex];
dt.Rows[row.DataItemIndex]["Part"] = ((TextBox)(row.Cells[1].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["Quantity"] = ((TextBox)(row.Cells[2].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["Ship-To"] = ((TextBox)(row.Cells[3].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["Requested Date"] = ((TextBox)(row.Cells[4].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["Shipping Method"] = ((DropDownList)(row.Cells[5].Controls[0])).SelectedItem.ToString();
//Reset the edit index.
griditems.EditIndex = -1;
//Bind data to the GridView control.
BindData();
Session["table"] = dt;
}
Note: The way you are trying to get the updating recording is not appropriate you should read more about how to access data on row updating.
How can i insert each time a diffrent row in datatable?
The data table is used in a dataGridView to write a log. I need each time to write in a diffrent line (row) in the datatable, when I can't know how many rows I need in runtime.
Another thing; the datatable is loaded from a XML file, so there might be already rows in the data table.
What can i do? (in short, I always write in the same row) in C#
EDIT:
here is the code:
From some reason, the DateGridView isonly having one row(This is a method that activated in a click of a button)
public void gridStart(string i, string b, string c)
{
DataTable dt = new DataTable();//empty table with no schema
DataColumn colContactID = new DataColumn("Date", typeof(string));
DataColumn colContactName = new DataColumn("Caller", typeof(string));
DataColumn colResult = new DataColumn("Result", typeof(string));
dt.Columns.Add(colContactID);
dt.Columns.Add(colContactName);
dt.Columns.Add(colResult);
DataRow row = dt.NewRow();
row["Date"] = i;
row["Caller"] = b;
row["Result"] = c;
dt.Rows.Add(row);
}
You should be able to Use DataTable.NewRow(). There are several samples on that MSDN page. If you have more questions please provide some sample code to your answer.
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.DataSource = MyDataTable;
}
private string _fileName = "MyCache.xml";
private DataTable _myDataTable;
public DataTable MyDataTable
{
get
{
if (_myDataTable == null)
{
_myDataTable = new DataTable();
if (File.Exists(_fileName))
_myDataTable.ReadXml(_fileName);
else
InitDataTable(_myDataTable);
}
return _myDataTable;
}
}
private void InitDataTable(DataTable table)
{
table.TableName = "MyTable";
table.Columns.Add("Date", typeof(DateTime));
table.Columns.Add("Caller", typeof(string));
table.Columns.Add("Result", typeof(string));
}
// Have your add code call this method!
private void AddValue(DateTime date, string caller, string result)
{
var row = MyDataTable.NewRow();
row["Date"] = date;
row["Caller"] = caller;
row["Result"] = result;
MyDataTable.Rows.Add(row);
}
protected override void OnClosed(EventArgs e)
{
if (_myDataTable != null)
_myDataTable.WriteXml(_fileName, XmlWriteMode.WriteSchema);
base.OnClosed(e);
}
If it is bound to a data source, you need to first get the data source,
// Assuming it's a DataTable
DataTable dt = ((DataTable)myDataGridView.DataSource);
insert rows to your data source (like what your method is doing in your post), then tell the view to refresh its contents.
So maybe something like this would work:
public void gridStart()
{
DataTable dt = new DataTable();
DataColumn colContactID = new DataColumn("Date", typeof(string));
DataColumn colContactName = new DataColumn("Caller", typeof(string));
DataColumn colResult = new DataColumn("Result", typeof(string));
dt.Columns.Add(colContactID);
dt.Columns.Add(colContactName);
dt.Columns.Add(colResult);
dataGridView1.DataSource = dt;
// Call method to insert values.
}
to start up the grid, and:
public void gridInsert(string i, string b, string c)
{
DataTable dt = (DataTable)myDataGridView.DataSource;
DataRow row = dt.NewRow();
row["Date"] = i;
row["Caller"] = b;
row["Result"] = c;
dt.Rows.Add(row);
// Call another method to refresh grid view.
}
to call when you want to insert data to your DataTable.
My solution:
public partial class _Default : System.Web.UI.Page
{
DataTable tb = new DataTable();
}
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
DataTable dt = new DataTable("table");
dt.Columns.Add(new DataColumn("NR", Type.GetType("System.Int32")));
dt.Columns.Add(new DataColumn("Dihname", Type.GetType("System.String")));
dt.Columns.Add(new DataColumn("ing", Type.GetType("System.String")));
dt.Columns.Add(new DataColumn("Cost", Type.GetType("System.String")));
Session["ss"] = dt;
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
tb = (DataTable)Session["ss"];
DataRow r1 = tb.NewRow();
r1[0] = ViewState["dishid"].ToString();
r1[1] = ViewState["dishname"];
r1[3] = Label3.Text;
tb.Rows.Add(r1);
DataList5.DataSource = tb;
DataList5.DataBind();
}
}