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"
Related
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.
This is my code to display table value to a DropDownList.
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Conn"].ConnectionString))
{
con.Open();
string str="SELECT ItemOne,ItemTwo,ItemThree FROM tableItem";
using (SqlCommand cmd = new SqlCommand(str, con))
{
SqlDataAdapter dA=new SqlDataAdapter(cmd);
dA.Fill(dT);
DropDownList1.DataSource = dT;
DropDownList1.DataValueField = "ItemTwo";
DropDownList1.DataTextField = "ItemOne";
DropDownList1.DataBind();
}
This is to display the selected value of DropDownList to a TextBox.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
TextBox1.Text = DropDownList1.SelectedValue.ToString();
TextBox2.Text = //Get the value of ItemThree here
}
My problem is: How will I display the column value of ItemThree in another TextBox.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
TextBox1.Text = DropDownList1.SelectedValue.ToString();
TextBox2.Text = DropDownList1.Items[2].ToString(); // 2 is your index
}
Another way of doing this
var connectionString = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
var sql = "SELECT ItemOne, ItemTwo, ItemThree FROM tableItem";
using (var table = new DataTable) {
using (var adapter = new SqlDataAdapter(sql, connectionString)
adapter.Fill(table);
foreach (DataRow dr in table.Rows)
DropDownList1.Items.Add(new ListItem(dr["ItemTwo"], dr["ItemTwo"]) {
Tag = dr["ItemThree"]
});
}
Then from the event handler
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
TextBox1.Text = DropDownList1.SelectedValue.ToString();
TextBox2.Text = DropdownList1.SelectedItem.Tag.ToString();
}
I've added an edit/update option to a Gridview of bound data from a table in my database TextBooks. I'm allowing this in case something changes down the road the admin can then edit/update the information. Currently I am able to click edit type in the information, and then it binds it to the current Grid on page, but doesn't save it to the database and upon leaving the page and returning to it, it is reverted back to the old value. After following the code to the BindGrid() method i believe I've gone wrong somewhere but cannot fully grasp what it is I'm missing.
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = new DataTable();
string query = "select * from textBooks ";
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["HUTDMSConnectionString"].ToString()))
using (SqlDataAdapter adapter = new SqlDataAdapter(query, connection))
adapter.Fill(dt);
ViewState["allBooks"] = dt;
this.BindGrid();
}
}
protected void BindGrid()
{
GridView1.DataSource = ViewState["allBooks"] as DataTable;
GridView1.DataBind();
}
protected void OnRowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
this.BindGrid();
}
protected void OnUpdate(object sender, EventArgs e)
{
GridViewRow row = (sender as LinkButton).NamingContainer as GridViewRow;
string Ancillary = (row.Cells[3].Controls[0] as TextBox).Text;
string BookActive = (row.Cells[4].Controls[0] as TextBox).Text;
string InactiveDate = (row.Cells[6].Controls[0] as TextBox).Text;
string Author = (row.Cells[7].Controls[0] as TextBox).Text;
string Publisher = (row.Cells[8].Controls[0] as TextBox).Text;
string EditionAndDate = (row.Cells[9].Controls[0] as TextBox).Text;
string Imprint = (row.Cells[10].Controls[0] as TextBox).Text;
string eISBN = (row.Cells[13].Controls[0] as TextBox).Text;
string ebookAvailable = (row.Cells[14].Controls[0] as TextBox).Text;
string Notes = (row.Cells[15].Controls[0] as TextBox).Text;
DataTable dt = ViewState["allBooks"] as DataTable;
dt.Rows[row.RowIndex]["Ancillary"] = Ancillary;
dt.Rows[row.RowIndex]["BookActive"] = BookActive;
dt.Rows[row.RowIndex]["InactiveDate"] = InactiveDate;
dt.Rows[row.RowIndex]["Author"] = Author;
dt.Rows[row.RowIndex]["Publisher"] = Publisher;
dt.Rows[row.RowIndex]["EditionAndDate"] = EditionAndDate;
dt.Rows[row.RowIndex]["Imprint"] = Imprint;
dt.Rows[row.RowIndex]["eISBN"] = eISBN;
dt.Rows[row.RowIndex]["ebookAvailable"] = ebookAvailable;
dt.Rows[row.RowIndex]["Notes"] = Notes;
ViewState["allBooks"] = dt;
GridView1.EditIndex = -1;
this.BindGrid();
}
So what you are currently doing is pulling data from a database, storing it in a gridview, then editing the data in the GridView. Once you call that databind command, that data becomes independent from the Database. In order to save this data to the database, I would recommend using SqlDataAdapter's Update method in the OnUpdate method. This will allow you to store the update values back to a datarow and save it to the database while following a similar strategy as when you fill the GridView.
I have a dropdownlist in a gridview and when the textbox is changed, I would like the selected value in the dropdownlists (three separate ones in total) to match the data in the database. The code in the textbox changed event is below:
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
DropDownList ddl = new DropDownList();
string connectionString = ConfigurationManager.ConnectionStrings["*******"].ConnectionString;
using (SqlConnection con = new SqlConnection(connectionString))
{
string query = "SELECT one, two, three FROM table WHERE id = " + TextBox1.Text;
SqlDataAdapter sda = new SqlDataAdapter(query, con);
DataSet ds = new DataSet();
int num = sda.Fill(ds);
if (num > 0)
{
GridView1.Visible = true;
GridView1.DataSource = ds;
GridView1.DataBind();
}
else
{
if (num == 0)
{
GridView1.Visible = false;
}
else
{
BindGrid();
}
}
}
Try using the RowDataBound event. For this to work, the drop-down-lists must already be populated with values, and in the event, the SelectedValue will be assigned.
protected void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// this assumes the drop-down-list columns are the first, second, and third columns (ordinal positions 0, 1, and 2)
DropDownList ddl1, ddl2, ddl3;
ddl1 = (DropDownList)e.Row.Cells[0].Controls[0];
ddl2 = (DropDownList)e.Row.Cells[1].Controls[0];
ddl3 = (DropDownList)e.Row.Cells[2].Controls[0];
DataRow currentRow = (DataRow)e.Row.DataItem;
ddl1.SelectedValue = currentRow[0].ToString();
ddl2.SelectedValue = currentRow[1].ToString();
ddl3.SelectedValue = currentRow[2].ToString();
}
}
I'm new in this and I'm a little lost.
Trying to show the values of my database in textbox by selecting in the combobox. But I can't.
Please help me. This is my code:
private void CargarDatos()
{
string consulta = "SELECT * FROM [dbo].[alumno]";
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(Properties.Settings.Default.conexion);
SqlCommand cmd = new SqlCommand(consulta, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
try
{
con.Open();
da.Fill(dt);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
con.Close();
this.dataGridView1.DataSource = dt;
cbalumno.DataSource = dt;
cbalumno.DisplayMember="Nombre";
cbalumno.ValueMember="Id";
}
private void Form1_Load(object sender, EventArgs e)
{
CargarDatos();
}
private void cbalumno_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
The parameters that i want to show are "Name" "Surname" and "DNI" of the table alumno.
Any ideas to how can I do that??
You can use DataRowView to get the record being bound with current SelectedItem. The Row property of DataRowView object will give you data row. Using this row you can get the columns being bound to it.
private void cbalumno_SelectedIndexChanged(object sender, EventArgs e)
{
DataRowView vrow = (DataRowView)cbalumno.SelectedItem;
string sValue = vrow.Row["Name"].ToString();
}
You already have placed the event cbalumno_SelectedIndexChanged in your code and now you have to use it.
Inside that event, just use the Text peroperty of that textbox and assign the value of the selected item in your combo box like this :
private void cbalumno_SelectedIndexChanged(object sender, EventArgs e)
{
yourTextBoxID.Text = comboBoxID.Text;
}
Hope this helps.