I have a GeidView in my form and I have a button which add new records to the GridView by adding a row to a Datatable and then make this DataTable as the GridContol's Data Source.
The problem is when I add a new record it display in the GridView but when I add another rocord it doesn't display in the GridView, The GridView always contains the first row I added to the DataTable !
So please could you help me to solve this problem ?
This is the source code :
private DataTable recompensesTable;
private void AjoutLivre_Load(object sender, EventArgs e)
{
recompensesTable = MakeRecomponsesTable();
recompenseGridControl.DataSource = recompensesTable;
}
private DataTable MakeRecomponsesTable()
{
DataTable recmpensesTable = new DataTable("Recompenses");
var anneeColumn = new DataColumn();
anneeColumn.DataType = Type.GetType("System.Int32");
anneeColumn.ColumnName = "Année";
recmpensesTable.Columns.Add(anneeColumn);
var prixLiteraireColumn = new DataColumn();
prixLiteraireColumn.DataType = Type.GetType("System.String");
prixLiteraireColumn.ColumnName = "Prix Litéraire";
recmpensesTable.Columns.Add(prixLiteraireColumn);
return recmpensesTable;
}
private void nouveauRecompense_Click(object sender, EventArgs e)
{
DataRow row = recompensesTable.NewRow();
row[0] = ajoutRecompense.KeyWordAnnee;
row[1] = ajoutRecompense.KeyWordPrixLiteraire;
recompensesTable.Rows.Add(row);
recompenseGridControl.DataSource = recompensesTable;
}
In your Page_Load you have recompensesTable = MakeRecomponsesTable();. That overwrites the changes and recreate the datatable values
On page postback, variables are restored to their default values and they need to be recreated. You can use Session to maintain your values
private void AjoutLivre_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
DataTable recompensesTable = MakeRecomponsesTable();
Session["recompensesTable"] = recompensesTable; //Save it to session the first time
recompenseGridControl.DataSource = recompensesTable;
}
}
and retrieve the session preserved value
private void nouveauRecompense_Click(object sender, EventArgs e)
{
DataTable recompensesTable = (DataTable) Session["recompensesTable"]; //retrieve it from session
DataRow row = recompensesTable.NewRow();
row[0] = ajoutRecompense.KeyWordAnnee;
row[1] = ajoutRecompense.KeyWordPrixLiteraire;
recompensesTable.Rows.Add(row);
Session["recompensesTable"] = recompensesTable; //save it back to session
recompenseGridControl.DataSource = recompensesTable;
}
change your
private void AjoutLivre_Load(object sender, EventArgs e)
{
recompensesTable = MakeRecomponsesTable();
recompenseGridControl.DataSource = recompensesTable;
}
To
private void AjoutLivre_Load(object sender, EventArgs e)
{
if(!IsPostback)
recompensesTable = MakeRecomponsesTable();
recompenseGridControl.DataSource = recompensesTable;
}
You also must save the datatable to session
the recmpensesTable is always a new DateTable, you should save it to session for next use.
Related
I want to add new row to existing datagridview. There is a problem beacause datagridview is connected to datasource and I can't add row by Rows.Add(). I have tried all commented lines and nothing works. Here is my code:
private void SaveButton_Click(object sender, EventArgs e)
{
if (start_tab == start_picker.ToString("dd-MM-yyyy HH:mm:00") & stop_tab != stop_picker.ToString("dd-MM-yyyy HH:mm:00"))
{
DateTime new_starttime = stop_picker;
DateTime new_stoptime = Convert.ToDateTime(stop_tab);
int new_cycletime = Convert.ToInt32(dataGridView3.Rows[dataGridView3.CurrentRow.Index].Cells["cycle_time"].Value) - Convert.ToInt32(textBox32.Text);
//devents.Rows.Add(new_starttime, new_stoptime, new_cycletime);
//DataTable devents = new DataTable();
//DataTable devents =
//DataRow newRow = devents.NewRow();
//newRow["start_time"] = new_starttime;
//newRow["stop_time"] = new_stoptime;
//newRow["cycle_time"] = new_cycletime;
//devents.Rows.Add(newRow);
dataGridView3.Rows.RemoveAt(dataGridView3.CurrentCell.RowIndex);
dataGridView3.Update();
dataGridView3.Refresh();
}
}
Data to datagridView is loaded from another private void:
private void Openbutton_Click(object sender, EventArgs e)
{
OpenReport();
EventClass eventData = new EventClass();
DataTable devents = eventData.Load_downtimes();
dataGridView3.DataSource = devents;
Adding to the DataTable should actually work.
The question is how you got devents here, it is declared locally in Openbutton_Click below.
You can best get it directly from the dgv (must be cast because DataSource can have various types)
var devents = (DataTable)dataGridView3.DataSource;
DataRow newRow = devents.NewRow();
newRow["start_time"] = new_starttime;
newRow["stop_time"] = new_stoptime;
newRow["cycle_time"] = new_cycletime;
devents.Rows.Add(newRow);
I have a gridview and some control below the griview. I insert values from "control" and press "Insert" button then the values are inserted into the gridview row. Here is the gridview image when I insert values in control
and press the "Insert" button
and when I click on the "edit" button in griview the values of the selected edit row are displayed below the "controls" but when I update values in the control and click again "insert" then the row automatically edits the data, but I don't want this, I want that when I click on "insert" again that the row should not display in edit mode, here is the image
I want that when I click on "insert" button that the row values are replaced with new values.
Here is my aspx.cs code:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.Add("ID", System.Type.GetType("System.Int32"));
dt.Columns.Add("Column Name", System.Type.GetType("System.String"));
dt.Columns.Add("Data Type", System.Type.GetType("System.String"));
dt.Columns.Add("Allow Null", System.Type.GetType("System.Boolean"));
dt.Columns.Add("Primary Key", System.Type.GetType("System.Boolean"));
Session["MyDataTable"] = dt;
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
DataTable t = (DataTable)Session["MyDataTable"];
DataRow row1 = t.NewRow();
row1["ID"] = t.Rows.Count + 1;
row1["Column Name"] = TextBox1.Text;
row1["Data Type"] = DropDownList1.Text;
row1["Allow Null"] = Null.Checked == true ? "true" : "false";
row1["Primary Key"] = Primary.Checked == true ? "true" : "false";
t.Rows.Add(row1);
Session["MyDataTable"] = t;
GridView2.DataSource = t;
GridView2.DataBind();
TextBox1.Text = String.Empty;
DropDownList1.Text = "Select DataType";
}
protected void GridView2_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
DataTable t = (DataTable)Session["MyDataTable"];
t.Rows.RemoveAt(e.RowIndex);
GridView2.DataSource = t;
GridView2.DataBind();
}
protected void GridView2_RowEditing(object sender, GridViewEditEventArgs e)
{
DataTable t = (DataTable)Session["MyDataTable"];
//GridView2.EditIndex = e.NewEditIndex;
// TextBox1.Enabled = true;
//GridViewRow row = GridView2.Rows[e.NewEditIndex];
TextBox1.Text = GridView2.Rows[e.NewEditIndex].Cells[2].Text.ToString();
DropDownList1.Text = GridView2.Rows[e.NewEditIndex].Cells[3].Text.ToString();
GridView2.DataSource = t;
GridView2.DataBind();
}
protected void GridView2_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
DataTable t = (DataTable)Session["MyDataTable"];
GridView2.EditIndex = -1;
GridViewRow row = GridView2.Rows[e.RowIndex];
GridView2.DataSource = t;
GridView2.DataBind();
}
public void cancel(object sender, GridViewCancelEditEventArgs e)
{
DataTable t = (DataTable)Session["MyDataTable"];
GridView2.EditIndex = -1;
GridViewRow row = GridView2.Rows[e.RowIndex];
GridView2.DataSource = t;
GridView2.DataBind();
}
private void tabControl1_Selected(object sender, TabControlEventArgs e)
{
if (e.TabPage.Name == tabPage2.Name)
{
table = Items.Get();
comboBox1.DataSource = table;
comboBox1.DisplayMember = "Item_ID";
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
DataTable temp = new DataTable();
string text = comboBox1.SelectedItem.ToString();
temp = Color.Get(text);
comboBox2.DataSource = temp;
comboBox2.DisplayMember = "Color_Name";
comboBox2.ValueMember = "Color_ID";
}
I am trying to populate the comboBox1 as the tabpage open and then populate the comboBox2 based on the selectedText of comboBox1.
comboBox_SelectedIndexChange runs 2 times when tab changes but returns null every times.
Note: I have already appended event handler as the form initializes like,
public Form1()
{
InitializeComponent();
tabControl1.Selected += new TabControlEventHandler(tabControl1_Selected);
comboBox1.SelectedIndexChanged += comboBox1_SelectedIndexChanged;
table = new DataTable();
s = new Stock();
}
First there is a bug in
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
DataTable temp = new DataTable();
string text = comboBox1.SelectedItem.ToString();
temp = Color.Get(text);
comboBox2.DataSource = temp;
comboBox2.DisplayMember = "Color_Name";
comboBox2.ValueMember = "Color_ID";
}
code. You override value for datasource in line
temp = Color.Get(text);
I think it should be like:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
DataTable temp = new DataTable();
string text = comboBox1.SelectedItem.ToString();
selectedColor = Color.Get(text);
comboBox2.DataSource = temp;
comboBox2.DisplayMember = "Color_Name";
comboBox2.ValueMember = "Color_ID";
comboBox2.SelectedItem = selectedColor;
}
I don't know contents of DataTable so instead of comboBox2.SelectedItem you may need to set SelectedItem, SelectedText or SelectedValue properties of comboBox2.
Suspicious line here:
string text = comboBox1.SelectedItem.ToString();
You will get text variable filled with "YourNamespace.DataTable". If your function Color.Get(text) is expecting Item_ID of selected item as parameter, then you should change that line of code above to:
string text = ((DataTable)comboBox1.SelectedItem).Item_ID;
I assumed that DataTable is an object that have Item_ID property.
private void tabControl1_Selected(object sender, TabControlEventArgs e)
{
if (e.TabPage.Name == tabPage2.Name)
{
table = Items.Get();
if (table.Rows.Count > 0)
{
//Update comboBox1 using table
comboBox1.DataSource = table;
comboBox1.DisplayMember = "Item_ID";
//Using 1st row and 1st coloumn in function argument to get colors
//Color.Get(string itemID) returns dataTable, which I used for comboBox2 DataSource
comboBox2.DataSource = Color.Get(table.Rows[0].ItemArray[0].ToString());
comboBox2.ValueMember = "Color_ID";
comboBox2.DisplayMember = "Color_Name";
}
}
}
Using Linq to sql through bindingsource control in WinForms, I could not get this to work:
private void textBox1_TextChanged(object sender, EventArgs e)
{
productBindingSource.Filter = string.Format("ProductName LIKE '*{0}*'", textBox1.Text);
MessageBox.Show("Changed");
}
NorthwindDataContext dc;
private void FrmFilter_Load(object sender, EventArgs e)
{
// create new data context
dc = new NorthwindDataContext();
// set the binding source data source to the full order table
var qry = (from p in dc.Products select p).ToList();
this.productBindingSource.DataSource = dc.GetTable<Product>();
}
When I type some letter in the textbox nothing happens in the datagridview.
Thanks for advices ...
Try changing your code to look like this:
NorthwindDataContext dc;
private void FrmFilter_Load(object sender, EventArgs e)
{
dc = new NorthwindDataContext();
this.productBindingSource.DataSource = dc.GetTable<Product>();
productDataGridView.DataSource = productBindingSource;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
this.productBindingSource.Filter = string.Format("ProductName LIKE '*{0}*'",
textBox1.Text);
}
Make sure your TextChanged event is wired up and actually running. Also, I took qry out of the example since you weren't using it anywhere in the posted code.
older edits:
You shouldn't have to reset the DataSource on the grid.
Try changing it to this:
private void textBox1_TextChanged(object sender, EventArgs e) {
if (textBox1.Text == string.Empty) {
productBindingSource.RemoveFilter();
} else {
productBindingSource.Filter = string.Format("ProductName LIKE '*{0}*'", _
textBox1.Text);
}
}
I would avoid worrying about replacing those special characters at the moment. Get the filter working first.
Here is a working example with just a DataGridView and a TextBox on a form:
private DataTable dt = new DataTable("Test");
private BindingSource bs;
public Form1() {
InitializeComponent();
dt.Columns.Add("ProductName", typeof(string));
DataRow dr1 = dt.NewRow();
dr1["ProductName"] = "One A";
dt.Rows.Add(dr1);
DataRow dr2 = dt.NewRow();
dr2["ProductName"] = "One B";
dt.Rows.Add(dr2);
DataRow dr3 = dt.NewRow();
dr3["ProductName"] = "Two A";
dt.Rows.Add(dr3);
DataRow dr4 = dt.NewRow();
dr4["ProductName"] = "Two B";
dt.Rows.Add(dr4);
bs = new BindingSource(dt, null);
dataGridView1.DataSource = bs;
}
private void textBox1_TextChanged(object sender, EventArgs e) {
if (textBox1.Text == string.Empty) {
bs.RemoveFilter();
} else {
bs.Filter = string.Format("ProductName LIKE '*{0}*'", textBox1.Text);
}
}
this work just fine for me!
this.productBindingSource.Filter = null;
I have a Click Event that fills a DataTable and the DataTable is the source of my GridView.
Then I have another click event that tries to get the GridView DataSource e converts it back to a DataTable Like:
DataTable dt = (DataTable)GridView1.DataSource;
But the Datasource returns null. Event if I put the code and the Page_Init event waiting for the right postBack
so I would like to know how can i persist the datasource of the gridview, or the DataTable
edited as required:
here is the whole code:
ps: the Page_Init was another try to get the datasource
private DataTable _dataTable;
public DataTable dataTable
{
get { return _dataTable; }
set { _dataTable = value; }
}
protected void Page_Init(object sender, EventArgs e)
{
if(Page.IsPostBack)
{
string ctrlname = BLL.Common.GetPostBackControlId(this.Page);
if(ctrlname == "ButtonDownload")
{
DataTable dt = (DataTable)GridView1.DataSource;
}
}
}
protected void Filter_Click(object sender, EventArgs e)
{
string[] status = new string[2];
status[0] = "Paga";
status[1] = "Disponivél";
dataTable = BLL.PagSeguro.GetTransactions(TextBoxInicio.Text, TextBoxFim.Text, status);
GridView1.DataSource = dataTable;
GridView1.DataBind();
}
protected void GetDataSource(object sender, EventArgs e)
{
DataTable dt = (DataTable)GridView1.DataSource;
}
This might work for you.
public partial class Demo : System.Web.UI.Page
{
private DataTable _myData = null;
protected DataTable MyData
{
get
{
if (null == _myData)
{
// You would load your data here.
_myData = new DataTable();
}
return _myData;
}
}
protected void Page_Load(object sender, EventArgs e)
{
// Lets say you set your data source here
myGrid.DataSource = this.MyData;
}
protected void Rendering(object sender, EventArgs e)
{
// This is some other event that also needs to get at the data.
DataTable mydata = this.MyData;
}
protected void Unload(object sender, EventArgs e)
{
if (null != _myData)
{
_myData.Dispose();
_myData = null;
}
}
I'm pretty sure you can only access the datasource that way through the DataBound event or ItemDataBound event. You might be able to access the DataRowView for each item in the Items collection, but I'm not sure:
DataRow row = ((DataRowView)GridView1.Rows[0].DataItem).Row;
As for persisting the datasource, you need to consider whether that's a good idea. Your options for storing the datasource are Session or Cache, but if the result set is fairly small it might be more efficient to make another round trip when you need the datasource. Whatever you decide to do, don't store it in ViewState.