EDIT: added a code and a image reference `public partial class DodavanjeNamirnice : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataTable dtTemp = new DataTable(); ;
dtTemp.Columns.Add(new DataColumn("Namirnica", typeof(string)));
dtTemp.Columns.Add(new DataColumn("Mjerna Jedinica", typeof(string)));
Session["Data"] = dtTemp;
}
}
protected void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["Data Source =.\\SQLEXPRESS; Initial Catalog = pra; Integrated Security = True"].ConnectionString;
string query = "SELECT * FROM Namirnica";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlDataAdapter sda = new SqlDataAdapter(query, con))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
var dataTableFromSession = Session["Data"] as DataTable;
var dataRow = dataTableFromSession.NewRow();
dataRow["Namirnica"] = DropDownList2.SelectedItem.Text;
dataRow["Mjerna Jedinica"] = CheckBoxList1.SelectedItem.Text;
dataTableFromSession.Rows.Add(dataRow);
Session["Data"] = dataTableFromSession;
GridView1.DataSource = dataTableFromSession;
GridView1.DataBind();
}
}`I got 2 dropdownlists , first one is filtering data in the 2nd,also 1st dropdownlist is connected to sql table as is the other one.
I have a checkbox which displays data from another table.
And my problem is: I want to add values I selected from 2nd dropdownlist and the checkboxlist to gridview in my webform.
I tried adding new columns manually but that ends up with displaying only first value from the dropdownlist, also displays only one value from the checkboxlist.
https://gyazo.com/59ea939b26deb55d3f31e68057249253
Set up a method to change the selected or created cell into a DataGridViewComboBoxCell and then feed it the datasource of your drop down list.
//could be whatever event you want such as the creation of a new DataRow in your DataGridView
private void gridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
dataGridView1[e.ColumnIndex, e.RowIndex] = new DataGridViewComboBoxCell();
DataGridViewComboBoxCell cb = (DataGridViewComboBoxCell)dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
cb.DataSource = dataSource;
}
You can do a similar thing for the checkbox but new DataGridViewCheckBoxCell() instead. After the user has selected a value you can just switch it back to being a regular cell if wanted.
Related
I have data in a DataTable object and I want to retrieve specific data from a data table on some certain conditions, for to query a data table using its select method
My database is MySQL 8.0.17 version
I tried this code without success because the error on VS 2019 is
The [ABW] column could not be found string
But the [ABW] don't is the name of column but value of column CountryCode
What's wrong with this code?
Please, any help?
DataTable cgv = new DataTable();
DataTable dtCustomers;
DataTable dtOrders;
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
// Create a datatable as a DataSource of GridViews
dtCustomers = new DataTable(); // parent gridview datasource
dtOrders = new DataTable(); // child gridview datasource
dtOrders = GetData("SELECT CountryCode, Language, IsOfficial, Percentage FROM `tCustomers`");
cgv = dtOrders; // set child datatable to temporary datatable
dtCustomers = GetData("SELECT CountryCode, Language, IsOfficial, Percentage FROM `tCustomers`;");
gvCustomers.DataSource = dtCustomers;
gvCustomers.DataBind();
}
}
protected void gvCustomers_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string CountryCode = gvCustomers.DataKeys[e.Row.RowIndex].Value.ToString();
GridView gvOrders = ((GridView)e.Row.FindControl("gvOrders"));
dtOrders.Columns[0].ColumnName = "CountryCode";
DataRow[] dr = dtOrders.Select(dtOrders.Columns[0].ColumnName + "=" + CountryCode.ToString());
gvOrders.DataSource = dr; // set child datatable to parent gridview as datasource
gvOrders.DataBind();
}
}
Like this:
protected void gvParent_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string CountryCode = gvCustomers.DataKeys[e.Row.RowIndex].Value.ToString();
GridView gvOrders = ((GridView)e.Row.FindControl("gvOrders"));
cgv.DefaultView.RowFilter = "CountryCode='" + CountryCode.ToString() + "'";
gvOrders.DataSource = cgv;
gvOrders.DataBind();
}
}
I have asked a similar question here but in my case I need to store multiple sets of datasets for an unknown number of times, not just once. So that is why I am asking here again.
I have multiple datatables with 2 columns in each datatable. One of them is a bool column (checkbox values). The checkbox values are empty when the form loads so up to user to check or uncheck them. Upon updating the checkbox, user press button1 to save only checkbox values in a dataset and this dataset will be saved in a List.
These datatables will then empty out and the same steps repeat for an unknown number of times (form loads empty datatables, user update checkboxes, user press button1). I have used the method below. No errors but when I want to display the List value in datagridview1 in Form2, it was empty. Below is my code. Hope to get help, thanks!
Class 1.cs (where I initiated my List)
public static List<string> list = new List<string>();
Form1.cs
//Create dataset
private DataSet Getdataset()
{
DataSet ds = new DataSet();
DataTable dt1 = new DataTable();
dt1.Columns.Add("Items", typeof(string));
dt1.Columns.Add("Status", typeof(bool));
dt1.Rows.Add("hello");
dt1.Rows.Add("hello");
ds.Tables.Add(dt1);
dgv1.DataSource = dt1;
dgv1.AllowUserToAddRows = false;
DataTable dt2 = new DataTable();
dt2.Columns.Add("Items", typeof(string));
dt2.Columns.Add("Status", typeof(bool));
dt2.Rows.Add("bye");
dt2.Rows.Add("bye");
ds.Tables.Add(dt2);
dgv2.DataSource = dt2;
dgv2.AllowUserToAddRows = false;
return ds;
}
//Save dataset in a List
private void button1_Click(object sender, EventArgs e)
{
DataSet dd = Getdataset();
foreach (DataTable table in dd.Tables)
{
foreach (DataRow row in table.Rows)
{
Class1.list.Add(Convert.ToString(row["Status"]));
}
}
Form2 f = new Form2();
f.ShowDialog();
}
Form2.cs
//Display dataset in datagridview
private void compile_VisibleChanged(object sender, EventArgs e)
{
DataGridViewRow row = (DataGridViewRow)dataGridView1.Rows[0].Clone();
foreach (string item in Class1.list)
{
row.Cells[0].Value = item;
}
dataGridView1.Rows.Add(row);
}
EDIT
As per er-sho comment, I added a messagebox in the code per below and it showed Systems.Collection.Generic.List1[System.String] 7 times (I have 6 checkboxes). There was still no display in the datagridview1 and I initialized the no. of columns, headers for datagridview1 to avoid compilation error. However, see below comment under Gokham’s solution (seems like the data in List is not per expected)
foreach (string item in Class1.list)
{
MessageBox.Show(Class1.list.ToString());
row.Cells[0].Value = item;
}
Everytime, when you click button1, you rewrite your data in dgv1 with default values:
DataTable dt1 = new DataTable();
dt1.Rows.Add("hello");
dt1.Rows.Add("hello");
dgv1.DataSource = dt1;
dt1 will be contains rows with only Item values, but not with Status. You should add code with getting user inputs
UPDATE
To achieve the goal you should make follow steps:
Init dgv1 - add columns and fill rows with default values
private void Form1_Load(object sender, EventArgs e)
{
UpdateDgv1();
}
private void UpdateDgv1()
{
DataSet ds = new DataSet();
DataTable dt1 = new DataTable();
dt1.Columns.Add("Items", typeof(string));
dt1.Columns.Add("Status", typeof(bool));
dt1.Rows.Add("hello");
dt1.Rows.Add("hello");
ds.Tables.Add(dt1);
dgv1.DataSource = dt1;
dgv1.AllowUserToAddRows = false;
}
Get values from dgv1 on button click
private void button1_Click(object sender, EventArgs e)
{
for (var i = 0; i < dgv1.Rows.Count; i++)
{
list.Add(Convert.ToString(dgv1.Rows[i].Cells[1].Value));
}
//restore dgv1
UpdateDgv1();
Form2 f = new Form2();
f.ShowDialog();
//clear list with old values or comment it
//if you want to save history of user inputs
list.Clear();
}
Show list content on datagridview1 of Form2
private void Form2_VisibleChanged(object sender, EventArgs e)
{
dataGridView1.ColumnCount = 1;
foreach (string item in Form1.list)
{
var newRow = dataGridView1.Rows.Add();
//if checkbox from Form1 not checked
if (item == string.Empty)
dataGridView1.Rows[newRow].Cells[0].Value = false.ToString();
else
dataGridView1.Rows[newRow].Cells[0].Value = item;
}
}
Your Getdataset() method doesn't fill Status column of the table. Try
private DataSet Getdataset()
{
DataSet ds = new DataSet();
DataTable dt1 = new DataTable();
dt1.Columns.Add("Items", typeof(string));
dt1.Columns.Add("Status", typeof(bool));
DataRow dr = dt1.NewRow();
dr["Items"] = "Hello";
dr["Status"] = checkBox1.Checked;
dt1.Rows.Add(dr);
ds.Tables.Add(dt1);
dgv1.DataSource = dt1;
dgv1.AllowUserToAddRows = false;
...
return ds;
}
I recommend you using BindingList instead of List and assigning the list as the DataSource for dataGridView1.
public static BindingList<string> list = new BindingList<string>();
Form 2
private void compile_VisibleChanged(object sender, EventArgs e)
{
dataGridView1.DataSource = Class1.list;
}
I think using FormLoad event handler instead of VisibleChanged should be better in your case.
Have a look : Binding List<T> to DataGridView in WinForm
I have used the following code to display data from a TextBox to a GridView without saving the data to the database(Two TextBoxes and a Button). When I enter the Name and City in the TextBoxes, and click on the Button, those values will be displayed in the Gridview. It is working as expected without any errors. But I want to tweak the code a bit so that the GridView should be able to add new data from the Textbox by retaining the old data as it is in the Gridview (multiple rows should be displayed in the Gridview instead of single rows).
It is a web-based ASP.NET application using C# coding (Visual Studio 2010).
Can you make the necessary changes to the code given below so as to implement the above functionality?
public partial class _Default : System.Web.UI.Page
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnTextDisplay_Click(object sender, EventArgs e)
{
DataColumn dc1 = new DataColumn("Name");
DataColumn dc2 = new DataColumn("City");
dt.Columns.Add(dc1);
dt.Columns.Add(dc2);
DataRow dr = dt.NewRow();
dr[0] = txtName.Text;
dr[1] = txtCity.Text;
dt.Rows.Add(dr);
gvDisplay.DataSource = dt;
gvDisplay.DataBind();
}
}
You have to persists your data between postbacks, you have many options here: by Session, ViewState, Cache and some other.
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostback)
{
dt = Session["data_table"] as DataTable;
}
}
protected void btnTextDisplay_Click(object sender, EventArgs e)
{
if (dt == null)
{
dt = new DataTable();
DataColumn dc1 = new DataColumn("Name");
DataColumn dc2 = new DataColumn("City");
dt.Columns.Add(dc1);
dt.Columns.Add(dc2);
}
DataRow dr = dt.NewRow();
dr[0] = txtName.Text;
dr[1] = txtCity.Text;
dt.Rows.Add(dr);
gvDisplay.DataSource = dt;
gvDisplay.DataBind();
Session["data_table"] = dt;
}
I have a webpage that has a Telerik RadComboBox in radgrid control on the page,and i have a SqlserverCe database.My issue is how can i write the code to bind the RadCombobox at page load event in asp.net please help me.....
Items are bound to RadComboBox basically in the same way as to an ASP.NET DropDownList.
You can bind the RadComboBox to ASP.NET 2.0 datasources, ADO.NET DataSet/DataTable/DataView, to Arrays and ArrayLists, or to an IEnumerable of objects. And of course you can add the items one by one yourself. With RadComboBox, you'll use RadComboBoxItems instead of ListItems.
In one way or other, you'll have to tell the combobox what is each item's text and value.
Working with Items in Server Side Code:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
RadComboBoxItem item1 = new RadComboBoxItem();
item1.Text = "Item1";
item1.Value = "1";
RadComboBox1.Items.Add(item1);
RadComboBoxItem item2 = new RadComboBoxItem();
item2.Text = "Item2";
item2.Value = "2";
RadComboBox1.Items.Add(item2);
RadComboBoxItem item3 = new RadComboBoxItem();
item3.Text = "Item3";
item3.Value = "3";
RadComboBox1.Items.Add(item3);
}
}
Binding to DataTable, DataSet, or DataView:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
SqlConnection con = new SqlConnection("Data Source=LOCAL;Initial Catalog=Combo;Integrated Security=True");
SqlDataAdapter adapter = new SqlDataAdapter("SELECT [Text], [Value] FROM [Links]", con);
DataTable links = new DataTable();
adapter.Fill(links);
combo.DataTextField = "Text";
combo.DataValueField = "Value";
combo.DataSource = links;
combo.DataBind();
}
}
EDIT: RadComboBox in a Grid:
Inside a RadGrid, it is perhaps easiest to use load on demand, by setting EnableLoadOnDemand="True" and handling the OnItemsRequested event.
protected void RadComboBox1_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
{
string sql = "SELECT [SupplierID], [CompanyName], [ContactName], [City] FROM [Suppliers] WHERE CompanyName LIKE #CompanyName + '%'";
SqlDataAdapter adapter = new SqlDataAdapter(sql,
ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString);
adapter.SelectCommand.Parameters.AddWithValue("#CompanyName", e.Text);
DataTable dt = new DataTable();
adapter.Fill(dt);
RadComboBox comboBox = (RadComboBox)sender;
// Clear the default Item that has been re-created from ViewState at this point.
comboBox.Items.Clear();
foreach (DataRow row in dt.Rows)
{
RadComboBoxItem item = new RadComboBoxItem();
item.Text = row["CompanyName"].ToString();
item.Value = row["SupplierID"].ToString();
item.Attributes.Add("ContactName", row["ContactName"].ToString());
comboBox.Items.Add(item);
item.DataBind();
}
}
You can also bind the combobox manually in the grid's OnItemDataBoundHandler event:
protected void OnItemDataBoundHandler(object sender, GridItemEventArgs e)
{
if (e.Item.IsInEditMode)
{
GridEditableItem item = (GridEditableItem)e.Item;
if (!(e.Item is IGridInsertItem))
{
RadComboBox combo = (RadComboBox)item.FindControl("RadComboBox1");
// create and add items here
RadComboBoxItem item = new RadComboBoxItem("text","value");
combo.Items.Add(item);
}
}
}
How to add the checkbox field in gridview programatically, what's wrong with my code?
try
{
string Data_source=#"Data Source=A-63A9D4D7E7834\SECOND;";
string Initial_Catalog=#"Initial Catalog=replicate;";
string User=#"User ID=sa;";
string Password=#"Password=two";
string full_con=Data_source+Initial_Catalog+User+Password;
SqlConnection connection = new SqlConnection(full_con);
connection.Open();
SqlCommand numberofrecords = new SqlCommand("SELECT COUNT(*) FROM dbo.Table_1", connection);
DataSet ds2 = new DataSet();
SqlDataAdapter testadaptor = new SqlDataAdapter();
testadaptor.SelectCommand = new SqlCommand("SELECT COUNT(*) FROM dbo.Table_1", connection);
testadaptor.Fill(ds2);
grid1.DataSource = ds2;
CheckBoxField c = new CheckBoxField();
grid1.Columns.Add(c);
grid1.DataBind();
numberofrecords.Dispose();
connection.Close();
connection.Dispose();
}
catch (Exception a)
{
Response.Write("Please check ");
Response.Write(a.Message.ToString());
Response.Write(a.Source.ToString());
}//catch
The CheckBoxField will probably want a value for the DataField property. This should match the column names or aliases in your query. (I don't think a checkbox will work with number results, though.)
Edited: didn't realize what you were trying to do. A template field and a regular checkbox should get you closer to what you want. Something like this?
e.g.
const int ColumnSelect = 0;
protected void Page_Load(object sender, EventArgs e)
{
//Get real data here.
DataTable dt = new DataTable();
dt.Columns.Add("count");
dt.Rows.Add(dt.NewRow());
dt.Rows[0][0] = "5";
GridView1.Columns.Add(new TemplateField());
BoundField b = new BoundField();
GridView1.Columns.Add(b);
b.DataField = "count";
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType != DataControlRowType.Header)
{
e.Row.Cells[ColumnSelect].Controls.Add(new CheckBox());
}
}
Edit #2: as for getting the value, you can certainly do this. Are you looking for a Javascript or server-side solution? Here's a simple example for server-side if you had a button click:
protected void Button1_Click(object sender, EventArgs e)
{
foreach(GridViewRow row in GridView1.Rows)
{
//Could also use (CheckBox)row.Cells[ColumnSelect].FindControl if you give the checkboxes IDs when generating them.
CheckBox cb = (CheckBox)row.Cells[ColumnSelect].Controls[0];
if (cb.Checked)
{
//Do something here.
}
}
}
I had to specify which checkbox object, like this
System.Web.UI.WebControls.CheckBox
Also I had to add this to the gridview aspx page
OnRowDataBound="GridView1_RowDataBound"