On Button click event I execute a new query i get a new table but i am unable to populate it on to the same grid view. Is there any why where i can use schema instead of dataTables.
private void GetData()//This method Displays the Datatable onto the Grid
{
int intCount = 0;
int.TryParse(txt_messagecount.Text, out intCount);
DataTable dtData = null;
//dtData = _objIMRSData.GetData(txt_fromdate.Text, txt_todata.Text, txt_messagecount.Text);
dtData = _objIMRSData.GetTransactionData( txt_fromdate.Text, txt_todata.Text,intCount );
grd_transactionLog.DataSource = dtData;
grd_transactionLog.DataBind();
dtData.Clear();
}
//On Button click event I execute a new query i get a new table
//but i am unable to populate it on to the same grid view
protected void btn_next_Click(object sender, EventArgs e)
{
int messageCount = int.Parse(txt_messagecount.Text);
string lastRecord = grd_transactionLog.Rows[messageCount-1].Cells[1].Text;
DataTable dtData1 = null;
//dtData = _objIMRSData.GetData(lastRecord, txt_todata.Text, txt_messagecount.Text);
dtData1 = _objIMRSData.GetTransactionData(lastRecord, txt_todata.Text, messageCount);
//grd_transactionLog.Columns.Clear();
grd_transactionLog.DataSource = dtData1;
grd_transactionLog.DataBind();
dtData1.Clear();
}
Reassign the datasource. In the click event do this.
grd_transactionLog.DataSource = null;
grd_transactionLog.DataSource = dtData1;
Related
In C# i can easily get data from a SQL DataBase and put it in a DataGrid with this code :
private void GetPcListBtn_Click(object sender, RoutedEventArgs e)
{
string service = (string)ServiceCB.SelectedValue;
comm = new SqlCommand("select T_COLLABORATEURS.CO_IDENT,T_PC.PC_ID,T_PC.PC_NOM,T_PC.PC_MODEL," +
"T_PC.PC_DATE_MES,T_PC.PC_COMM,T_PC.SERV_ID from T_COLLABORATEURS, T_PC" +
$" where T_COLLABORATEURS.CO_ID = T_PC.CO_ID and T_PC.SERV_ID = '{service}' ", conn);
SqlDataAdapter dap = new SqlDataAdapter(comm);
DataTable dt = new DataTable();
dap.Fill(dt);
PC_DT.ItemsSource = dt.DefaultView;
}
Then on Datagrid SelectionChanged Event i can click on a row to get fields datas and put it in a texbox with this code :
// DataGrid SelectionChanged => Fill TexBox
private void PC_DT_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (PC_DT.SelectedItem is DataRowView oData)
{
string pcNom = (string)oData["PC_NOM"];
string pcModel = (string)oData["PC_MODEL"];
RefPcTxtBox.Text = $"{pcNom} / {pcModel}";
}
}
Now in a other application i want to use Linq To SQL to do exactly the same.
Fill DataGrid :
// Fill DataGrid
private void GetPcListBtn_Click(object sender, RoutedEventArgs e)
{
string service = (string)ServiceCB.SelectedValue;
DataClasses1DataContext dc = new DataClasses1DataContext();
var pcCo = from co in dc.T_COLLABORATEURS
join pc in dc.T_PC on co.CO_ID equals pc.CO_ID
where pc.SERV_ID == service
select new
{
pc.PC_ID,
co.CO_IDENT,
pc.PC_NOM,
pc.PC_MODEL,
pc.PC_DATE_MES,
pc.PC_COMM,
pc.SERV_ID
};
PC_DT.ItemsSource = pcCo;
}
But now how can i fill my TextBox by clicking a DataGrid row ??
private void PC_DT_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// How to Fill my Textbox ??
}
Please try this.
First way:
// Or whenever grid you want to use please set this type
var Grid = sender as DataGrid;
if(Grid != null)
{
textbox = Grid.FieldName
}
Second way:
var currentRow = GridName.SelectedRows;
if(currentRow != null)
{
textbox = currentRow .FieldName
}
I would like to create a datagridview with 4 columns. The first column contains an edit button per row. The second contains a delete button and the next columns should contain the object data to display like ID, Firstname and so on.
For the buttons I use the DataGridViewButtonColumn for the other ones I use the DataGridViewColumn. When running the program I initialize the datagridview once after initializing the form.
When adding a new row I create the two buttons and try to fill these four columns.
So this is my code
public partial class FrmMain : Form
{
public FrmMain()
{
InitializeComponent();
InitializePeopleList();
}
private void InitializePeopleList()
{
DataGridViewButtonColumn editButtonColumn = new DataGridViewButtonColumn();
DataGridViewButtonColumn deleteButtonColumn = new DataGridViewButtonColumn();
DataGridViewColumn idColumn = new DataGridViewColumn();
idColumn.HeaderText = "ID";
DataGridViewColumn firstNameColumn = new DataGridViewColumn();
firstNameColumn.HeaderText = "FirstName";
dgvPeople.Columns.Add(editButtonColumn);
dgvPeople.Columns.Add(deleteButtonColumn);
dgvPeople.Columns.Add(idColumn);
dgvPeople.Columns.Add(firstNameColumn);
}
private void CreatePerson()
{
// open a new dialog, create a new Person object and add it to the data list
AddPersonRow(newPerson); // Update GUI
}
private void AddPersonRow(Person newPerson)
{
DataGridViewRow personRow = new DataGridViewRow(); // Create a new row
Button editButton = new Button(); // create a new edit button for the first column
editButton.Text = "Edit";
editButton.Click += (object sender, EventArgs e) => UpdatePersonFirstName(newPerson.ID, personRow.Cells[3]);
Button deleteButton = new Button(); // create a new delete button for the second column
editButton.Text = "Delete";
editButton.Click += (object sender, EventArgs e) => RemovePerson(newPerson.ID, personRow);
personRow.Cells[0].Value = editButton;
personRow.Cells[1].Value = deleteButton;
personRow.Cells[2].Value = newPerson.ID; // Display the ID in the third column
personRow.Cells[3].Value = newPerson.FirstName; // Display the First Name in the fourth column
dgvPeople.Rows.Add(personRow); // add this row to the datagridview
}
private void RemovePerson(Guid personId, DataGridViewRow personRow)
{
// Remove the person from the data list
dgvPeople.Rows.Remove(personRow); // Update GUI
}
private void UpdatePersonFirstName(Guid personId, DataGridViewCell firstNameCell)
{
// open a new dialog and edit the Person
// update the person in the data list
firstNameCell.Value = updatedFirstName;
}
}
When I run the program the code crashes when I try to add a new person to the datagridview at AddPersonRow at
personRow.Cells[0].Value
I get an ArgumentOutOfRangeException because personRow.Cells has a Count of 0.
How can I add a new row to the datagridview that has two button columns and two text columns?
Initialization:
var editButtonColumn = new DataGridViewButtonColumn();
editButtonColumn.Text = "Edit";
editButtonColumn.UseColumnTextForButtonValue = true;
var deleteButtonColumn = new DataGridViewButtonColumn();
deleteButtonColumn.Text = "Delete";
deleteButtonColumn.UseColumnTextForButtonValue = true;
var idColumn = new DataGridViewTextBoxColumn();
idColumn.HeaderText = "ID";
var firstNameColumn = new DataGridViewTextBoxColumn();
firstNameColumn.HeaderText = "FirstName";
dgvPeople.Columns.Add(editButtonColumn);
dgvPeople.Columns.Add(deleteButtonColumn);
dgvPeople.Columns.Add(idColumn);
dgvPeople.Columns.Add(firstNameColumn);
dgvPeople.CellContentClick += DgvPeople_CellContentClick;
No need to create buttons. They will be created automatically because DataGridViewButtonColumn is used.
private void AddPersonRow(Person newPerson)
{
var rowIndex = dgvPeople.Rows.Add();
var row = dgvPeople.Rows[rowIndex];
row.Cells[2].Value = newPerson.ID;
row.Cells[3].Value = newPerson.FirstName;
}
Here we react to button presses:
private void DgvPeople_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0) // exclude header
{
if (e.ColumnIndex == 0)
{
// edit action
}
else if (e.ColumnIndex == 1)
{
// delete action
//dgvPeople.Rows.RemoveAt(e.RowIndex);
}
}
}
I have a GridView filled in using an object this way:
Ingreso I = new Ingreso();
I.ID_Producto = ID_Producto;
I.Producto = cmb_producto.Text;
I.ID_Productor = ID_Productor;
I.Productor = cmb_productor.Text;
I.Fecha_Ingreso = Fecha.Value.Date;
I.Cantidad = Convert.ToInt16(txt_cantidad_ingresada.Text);
I.Precio_Unitario = Convert.ToDecimal(txt_precio_unitario.Text);
I.Descripcion = txt_descripcion.Text;
Ingresos.Add(I);
ListadeIngresos = new BindingList<Ingreso>(Ingresos);
BindingSource source = new BindingSource(ListadeIngresos, null);
Grid_Ingreso.DataSource = source;
Then user needs to delete a row that was added, I'm trying this way:
private void Grid_Ingreso_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
{
int index = e.Row.Index;
Ingresos.RemoveAt(index);
ListadeIngresos.RemoveAt(index);
BindingSource source = new BindingSource(ListadeIngresos, null);
Grid_Ingreso.DataSource = source;
}
My problem is that the row gets deleted three times from the gridview and the object (Ingresos). It's like the event firing 3 times, but when I debug I only see it entering once. Why this is happening?
Thanks
I'm quite new to ASP.NET and I need your help.
I'm programming on an application which should help to fix frequent issues. Users can click the displayed cases if it describes their problem. The application searches for more cases or displays a possible solution.
Now what I need for this is some code which creates the buttons dynamically. I googled some ideas and created some code, however I was not able to get it to work.
It works to create the first selection of buttons with the Default_Load method. Also the OnClick event (ButtonClick_System) works fine which means I get the next selection.
From here it starts messing around. The dynamic buttons created in ButtonClick_System don't have a working OnClick action.
Instead of proceeding with ButtonClick_Question (because of btn_system.Command += ButtonClick_Question; in ButtonClick_System) it seems like it just loads the homepage (maybe something wrong with Page_Load?).
The application should do ButtonClick_Question until no more datasets available in database.
I got the following code:
using System;
using System.Configuration;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Data;
using Oracle.DataAccess.Client;
namespace Application
{
public partial class _default : System.Web.UI.Page
{
// Variables
private string app_name = "Application";
// ----- Page_Load ----- //
protected void Page_Load(object sender, EventArgs e)
{
Default_Load();
Session["Application"] = app_name;
}
// ----- Methods ----- //
// Load homepage
public void Default_Load()
{
pnl_default.Visible = true;
pnl_content.Visible = false;
HtmlGenericControl html_default = new HtmlGenericControl();
html_default.TagName = "div";
string cmdString = "(...)";
DataTable dtSystems = OraQueryData(cmdString);
foreach (DataRow dtRow in dtSystems.Rows)
{
int system_id = Convert.ToInt32(dtRow["SYSTEM_ID"]);
string system_name = Convert.ToString(dtRow["SYSTEM_NAME"]);
var btn_system = new Button
{
ID = "btn_" + system_name,
Text = system_name,
CssClass = "sys_buttons"
};
btn_system.Command += ButtonClick_System;
btn_system.CommandArgument = Convert.ToString(system_id);
html_default.Controls.Add(btn_system);
}
plh_default.Controls.Clear();
plh_default.Controls.Add(html_default);
}
// Button OnClick Events
protected void ButtonClick_System(object sender, CommandEventArgs e)
{
pnl_default.Visible = false;
pnl_content.Visible = true;
HtmlGenericControl html_questions = new HtmlGenericControl();
html_questions.TagName = "div";
int system_id = Convert.ToInt32(e.CommandArgument);
string cmdString = "(...)";
DataTable dtQuestions = OraQueryData(cmdString);
foreach (DataRow dtRow in dtQuestions.Rows)
{
string question_id = Convert.ToString(dtRow["FRAGE_ID"]);
string question_text = Convert.ToString(dtRow["FRAGE_TEXT"]);
var btn_system = new Button
{
ID = "btn_question" + question_id,
Text = question_text,
CssClass = "quest_buttons"
};
btn_system.Command += ButtonClick_Question;
btn_system.CommandArgument = Convert.ToString(system_id);
html_questions.Controls.Add(btn_system);
}
plh_content.Controls.Clear();
plh_content.Controls.Add(html_questions);
}
protected void ButtonClick_Question(object sender, CommandEventArgs e)
{
pnl_default.Visible = false;
pnl_content.Visible = true;
HtmlGenericControl html_ChildQuestions = new HtmlGenericControl();
html_ChildQuestions.TagName = "div";
int parent_id = Convert.ToInt32(e.CommandArgument);
string cmdString = "(...)";
DataTable dtChildQuestions = OraQueryData(cmdString);
foreach (DataRow dtRow in dtChildQuestions.Rows)
{
string question_id = Convert.ToString(dtRow["FRAGE_ID"]);
string question_text = Convert.ToString(dtRow["FRAGE_TEXT"]);
var btn_system = new Button
{
ID = "btn_question" + question_id,
Text = question_text,
CssClass = "quest_buttons"
};
btn_system.Command += ButtonClick_Question;
btn_system.CommandArgument = question_id;
html_ChildQuestions.Controls.Add(btn_system);
}
plh_content.Controls.Clear();
plh_content.Controls.Add(html_ChildQuestions);
}
// ----- Oracle Data Query Methods ----- //
// Create and execute query on database
public static DataTable OraQueryData(string cmdString)
{
string conString = ConfigurationManager.AppSettings["Connection"];
OracleConnection oraCon = new OracleConnection(conString);
OracleCommand oraCmd = new OracleCommand(cmdString, oraCon);
OracleDataAdapter oraDtAd = new OracleDataAdapter(oraCmd.CommandText, oraCon);
DataTable dt = new DataTable();
oraCon.Open();
oraDtAd.Fill(dt);
oraCon.Close();
return dt;
}
}
}
If I've understood the issue correctly I think you're using the wrong controls for the wrong usages.
What I'd suggest you need to do is bind the collection of FAQ records to a repeater or some other data set display control. You can then have an event on the repeater which can handle which record ID has been clicked, post back with that value and refresh the collection of data from that (maybe in another repeater). Don't dynamically create buttons and bind events to them otherwise you will end up in a mess.
Hope this helps.
Everything should work, but i can't figure out why i can't get the value from the ddl. I know the code is not too clean.
protected void gridProduse_RowEditing(object sender, GridViewEditEventArgs e)
{
gridProduse.EditIndex = e.NewEditIndex;
gridProduse.DataBind();
using (var context = new SATContext())
{
var query = from t in context.TipuriProduse
select t.Denumire;
DropDownList list = new DropDownList();
list.DataSource = query.ToList();
list.DataBind();
list.ID = "ddlTipProdus";
list.Height = 27;
DropDownList listMoneda = new DropDownList();
listMoneda.ID = "ddlMoneda";
listMoneda.Items.Add("RON");
listMoneda.Items.Add("EUR");
listMoneda.Items.Add("USD");
listMoneda.Height = 27;
gridProduse.Rows[e.NewEditIndex].Cells[7].Controls.Add(list);
gridProduse.Rows[e.NewEditIndex].Cells[6].Controls.Add(listMoneda);
gridProduse.Rows[e.NewEditIndex].Cells[6].Controls[0].Visible = false;
gridProduse.Rows[e.NewEditIndex].Cells[7].Controls[0].Visible = false;
}
}
protected void gridProduse_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = gridProduse.Rows[e.RowIndex];
Produs prod = new Produs();
prod.ProdusId = Convert.ToInt32(((TextBox)(row.Cells[2].Controls[0])).Text);
prod.Denumire = ((TextBox)(row.Cells[3].Controls[0])).Text;
DropDownList ddl = (DropDownList)gridProduse.Rows[e.RowIndex].FindControl("ddlMoneda");
prod.Moneda = ddl.SelectedValue; // this is where i get the error
//prod.Moneda = ((row.FindControl("ddlMoneda") as DropDownList)).SelectedValue;
prod.PretCuTVA = Convert.ToInt32(((TextBox)(row.Cells[5].Controls[0])).Text);
prod.PretFaraTVA = Convert.ToInt32 (((TextBox)(row.Cells[4].Controls[0])).Text);
lit1.Text = prod.ProdusId.ToString();
using (var context = new SATContext())
{
IRepository<Produs> ProdusRepository = new ProdusRepository();
ProdusRepository.Update(prod);
}
gridProduse.EditIndex = -1;
gridProduse.DataBind();
Response.Redirect("Produse.aspx");
}
And this is the error:
An exception of type 'System.NullReferenceException' occurred in Licenta.dll but was not handled in user code
Additional information: Object reference not set to an instance of an object.
I'm pretty sure that you need to select a cell before you can reliably call `FindControl'
(DropDownList)gridProduse.Rows[e.RowIndex].Cells[SomeCell].FindControl("ddlMoneda");
Since your listMoneda control is being created dynamically after the Page_Init event, it is not being registered in the ViewState, and thus cannot be found on PostBack. Read this explanation for a solution