Datagridview Column width not changing - c#

this is the property | this is the pic
i cant seem to resize my column width in Datagridview. Here is my code:
public void dgvwidth()
{
crud.FillDataGrid("Select ProductID,BrandName,Dosage from ProductItems", ref dgvOrderproductlist);
dgvOrderproductlist.Columns[0].Width = 80;
dgvOrderproductlist.Columns[1].Width = 250;
dgvOrderproductlist.Columns[2].Width = 80;
}
private void HomePage_Load(object sender, EventArgs e)
{
dgvwidth();
}
I'm trying to get just 3 columns from my table and change it column width to fit my Datagridview. its not getting any error but its not changing the column width as well.
public void FillDataGrid(string sql, ref DataGridView dg)
{
try
{
DataSet ds = new DataSet();
cn.Open();
cmd = new SqlCommand(sql, cn);
adptr = new SqlDataAdapter(cmd);
adptr.Fill(ds);
dg.DataSource = "";
dg.DataSource = ds.Tables[0];
dg.AutoResizeColumns();
}
catch (Exception e)
{
MessageBox.Show("" + e.Message);
}
cn.Close();
}

Can you try like this
public void dgvwidth()
{
crud.FillDataGrid("Select ProductID,BrandName,Dosage from ProductItems", ref dgvOrderproductlist);
var column = dgvOrderproductlist.Columns[0];
column.Width = 80;
column = dgvOrderproductlist.Columns[1];
column.Width = 250;
column = dgvOrderproductlist.Columns[2];
column.Width = dgvOrderproductlist.Width - dgvOrderproductlist.Columns[0].Width - dgvOrderproductlist.Columns[1].Width - 50;
}

Related

How to fill datagridview cells with database content when column combobox is selected

I know how to fill textboxes with its values from the SQL database when combobox selectedindexchnged is fired. I tried to do so with datagridview but the column "Position" is not showing any value from the SQL database. Below are screenshot and codes l have tried. Kindly assist.
private void columncomboselectedindex_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'northwindDataSet5.employeeSCL2' table. You can move, or remove it, as needed.
this.employeeTableAdapter.Fill(this.northwindDataSet5.employee);
DataGridViewComboBoxColumn comboCol = new DataGridViewComboBoxColumn();
comboCol.Name = "FullName";
comboCol.DataSource = employeeBindingSource;
comboCol.ValueMember = "EmployeeID";
comboCol.Width = 200;
comboCol.DisplayMember = "FullName";
dataGridView1.Columns.Add(comboCol);
DataGridViewTextBoxColumn priceCol = new DataGridViewTextBoxColumn();
priceCol.Name = "Position";
dataGridView1.Columns.Add(priceCol);
}
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
cmd = new SqlCommand("SELECT Position FROM employee WHERE FullName = '" + dataGridView1.Rows[0].Cells["FullName"].Value + "'", con);
con.Open();
cmd.ExecuteNonQuery();
SqlDataReader DR;
DR = cmd.ExecuteReader();
while (DR.Read())
{
string Position = (string)DR["Position"].ToString();
dataGridView1.Rows[0].Cells["Position"].Value = Position;
}
con.Close();
}

DataGridViewComboBoxCell valueValue is invalid with binded DataGridViewComboBoxCell

I have a DatagridView with two DataGridViewComboBoxCell:
Administration
Employee.
What I want to do is when I select an administration from 1st
DataGridViewComboBoxCell, I'll get the list of the employees of selected
Admininstration in the 2nd DataGridViewComboBoxCell. I binded the first
DataGridViewComboBoxCell manually to administrationBindingSource and I tried
this answer code, This is the code I used:
dataGridView1.CellValueChanged += new DataGridViewCellEventHandler(dataGridView1_CellValueChanged);
dataGridView1.CurrentCellDirtyStateChanged += new EventHandler(dataGridView1_CurrentCellDirtyStateChanged);
void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
if (dataGridView1.IsCurrentCellDirty)
{
// This fires the cell value changed handler below
dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex == -1)
{
return;
}
DataGridViewComboBoxCell cb = (DataGridViewComboBoxCell)dataGridView1.CurrentRow.Cells["administrationColumn"];
int item = 0;
if (cb.Value != null)
{
item = (Int32)cb.Value;
selectEmployee(item);
dataGridView1.Invalidate();
}
}
private void selectEmployee(int idAdministration)
{
if (con.State != ConnectionState.Open)
{
con.Open();
}
SqlCommand Cmd = new SqlCommand("SELECT * FROM Employee WHERE IdAdministration = #idAdministration", con);
Cmd.Parameters.AddWithValue("#idAdministration", idAdministration);
DataTable Dt = new DataTable();
Dt.Load(Cmd.ExecuteReader());
DataGridViewComboBoxCell cb = (DataGridViewComboBoxCell)dataGridView1.CurrentRow.Cells["Employee"];
cb.DataSource = Dt;
cb.DisplayMember = "Name";
cb.ValueMember = "CodeEmployee";
con.Close();
}
This code works fine in the first time but when I try to update admininstration value I got this error message:
DataGridViewComboBoxCell value is invalid
How to fix it?
Try to clear the value of employee cell before rebind it in the void
"selectEmployee", something like:
private void selectEmployee(int idAdministration)
{
if (con.State != ConnectionState.Open)
{
con.Open();
}
SqlCommand Cmd = new SqlCommand("SELECT * FROM Employee WHERE IdAdministration = #idAdministration", con);
Cmd.Parameters.AddWithValue("#idAdministration", idAdministration);
DataTable Dt = new DataTable();
Dt.Load(Cmd.ExecuteReader());
DataGridViewComboBoxCell cb = (DataGridViewComboBoxCell)dataGridView1.CurrentRow.Cells["Employee"];
cb.Value = null; //add this
cb.DataSource = Dt;
cb.DisplayMember = "Name";
cb.ValueMember = "CodeEmployee";
con.Close();
}

How to add new row on click winforms

I have a winforms application that I am developing, I have hit a dead end. What I am trying to do is on each "click", add a new row to my DataTable with the values input in the form. This Datatable is the DataSource for my DataGridView. Can someone point me in the right direction on how this can be achieved.
Articles I looked at:
How to add new row to datatable gridview
My code:
private void btnAdd_Click(object sender, EventArgs e)
{
//inserting into order table
DataTable dt = new DataTable();
string articleId = cmbArticle.Text;
string productDescription = txtDesc.Text;
string type = txtType.Text;
string materialType = txtMaterial.Text;
string size = cmbSizes.Text;
string quantity = txtQuantity.Text;
try
{
dt.Columns.Add("Article");
dt.Columns.Add("Description");
dt.Columns.Add("Type");
dt.Columns.Add("Material");
dt.Columns.Add("Size");
dt.Columns.Add("Quantity");
dt.Columns.Add("DateTime");
DataRow dr = dt.NewRow();
//addrows
dr["Article"] = articleId;
dr["Description"] = productDescription;
dr["type"] = type;
dr["Material"] = materialType;
dr["Size"] = size;
dr["Quantity"] = quantity;
dt.Rows.Add(dr);
dgvView.DataSource = dt;
}
catch (Exception ex)
{
}
}
On each click you are creating a new DataTable which would be with just one row, You need to create DataTable once and then just keep adding rows to in the click. Define your DataTable at class level and then in your event just add a new row to it.
DataTable dt = new DataTable(); //at class level
private void Form1_Load(object sender, EventArgs e)
{
CreateDataTableColumns();
//.... your code
}
Then have a method to create table structure, call that method once from your From_Load event.
private void CreateDataTableColumns()
{
dt.Columns.Add("Article");
dt.Columns.Add("Description");
dt.Columns.Add("Type");
dt.Columns.Add("Material");
dt.Columns.Add("Size");
dt.Columns.Add("Quantity");
dt.Columns.Add("DateTime");
}
Later add rows to your class level DataTable in Add event.
private void btnAdd_Click(object sender, EventArgs e)
{
string articleId = cmbArticle.Text;
string productDescription = txtDesc.Text;
string type = txtType.Text;
string materialType = txtMaterial.Text;
string size = cmbSizes.Text;
string quantity = txtQuantity.Text;
try
{
DataRow dr = dt.NewRow();
//addrows
dr["Article"] = articleId;
dr["Description"] = productDescription;
dr["type"] = type;
dr["Material"] = materialType;
dr["Size"] = size;
dr["Quantity"] = quantity;
dt.Rows.Add(dr);
dgvView.DataSource = dt;
}
catch (Exception ex)
{
}
}
(I believe you are doing something with the exception object in your catch block, like logging, showing message to user etc)

Creating column Combobox in Datagridview

I am new to C#. I want to create combobox in first column of my Datagridview. Following is the routine I have wrote. But it is adding combo in last column after setting up my grid.
For setting up Grid, i have tried the below code:
private void SetGrid()
{
dgDetail.AutoGenerateColumns = false;
dgDetail.ColumnCount = 5;
dgDetail.Columns[0].Name = "Debit";
dgDetail.Columns[0].HeaderText = "Debit Account Name";
dgDetail.Columns[1].Name = "Bank";
dgDetail.Columns[1].HeaderText = "Bank";
dgDetail.Columns[2].Name = "ChqNo";
dgDetail.Columns[2].HeaderText = "CC/Chq No";
dgDetail.Columns[3].Name = "ChqDate";
dgDetail.Columns[3].HeaderText = "Chq Date";
dgDetail.Columns[4].Name = "Amount";
dgDetail.Columns[4].HeaderText = "Amount";
dgDetail.AllowUserToDeleteRows = true;
dgDetail.Columns[0].Width = 280;
dgDetail.Columns[1].Width = 160;
dgDetail.Columns[2].Width = 90;
dgDetail.Columns[3].Width = 90;
dgDetail.Columns[4].Width = 120;
dgDetail.RowsDefaultCellStyle.ForeColor = Color.Black;
dgDetail.RowsDefaultCellStyle.BackColor = Color.White;
dgDetail.Font = new Font("Arial", 9, FontStyle.Regular);
}
For Creating the combobox which is filled from DB.
private void FillGridCombo()
{
SqlConnection sqlConnection = new SqlConnection(strCon);
sqlConnection.Open();
try
{
string selectQueryStringMonth = "SELECT accode, GLAC FROM glmast where (actype = 'CSH' and titleac <> 'PDP') OR TITLEAC = 'DIS' ORDER BY GLAC";
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(selectQueryStringMonth, sqlConnection);
SqlCommandBuilder sqlCommandBuilder = new SqlCommandBuilder(sqlDataAdapter);
DataTable dataTable = new DataTable();
sqlDataAdapter.Fill(dataTable);
BindingSource bindingSourceMonth = new BindingSource();
bindingSource.DataSource = dataTable;
//Adding Combo
DataGridViewComboBoxColumn ColumnAcc = new DataGridViewComboBoxColumn();
ColumnAcc.DataPropertyName = "Debit Account Name";
ColumnAcc.HeaderText = "Debit Account Name";
ColumnAcc.Width = 280;
ColumnAcc.DataSource = bindingSourceMonth;
ColumnAcc.ValueMember = "accode";
ColumnAcc.DisplayMember = "GLAC";
dgDetail.Columns.Add(ColumnAcc);
dgDetail.DataSource = bindingSource;
}
catch (Exception ex)
{
MessageBox.Show("Error : " + ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
if (sqlConnection.State != ConnectionState.Closed)
sqlConnection.Close();
}
}
I am calling both procedures on my NewData() like this.
private void NewData()
{
if (dgDetail.DataSource != null)
dgDetail.DataSource = null;
else
dgDetail.Rows.Clear();
ClearData();
CtrlEnable();
SetGrid();
FillGridCombo();
}
Help / Guide me to achieve this.,
use
dgDetail.Columns.Insert(0, ColumnAcc);
instead of
dgDetail.Columns.Add(ColumnAcc);
when you use Add it simply adds it as the last column, while using Insert you can choose where to add it to.
public virtual void Insert( int columnIndex, DataGridViewColumn
dataGridViewColumn )
note that the columnIndex is a zero-based index so 0 is the first column
You can use the Insert method instead of Add like this:
dgDetail.Columns.Insert(0,ColumnAcc);

Apply Column Filtering in Gridview in asp.net

I have a gridview which is populated at runtime with a table with unknow number of columns which are not known before hand.
I want to apply column filtering on all columns with Drop Down List.
How can I achieve it. Using Jquery, Linq or simple C sharp Coding.
public partial class DetailView : System.Web.UI.Page
{
public static int y = 0;
public static String colName = "";
public static Boolean flag = false;
static String folder = "";
static public MySqlConnection conn = null;
static public DropDownList dp = null;
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
string strcon = ConfigurationManager.ConnectionStrings["abc"].ConnectionString;
conn = new MySqlConnection(strcon);
conn.Open();
Response.Write(Session["cols"].ToString());
Response.Write(Session["id"].ToString());
// Response.Write("qw");
folder = Session["folderName"].ToString();
colName = Session["cols"].ToString();
GridBind(folder, colName, flag);
}
protected void Page_Load(object sender, EventArgs e)
{
}
public void GridBind(String folder, String colName, Boolean val)
{
GridView1.DataSource = null;
GridView1.DataBind();
GridView1.Columns.Clear();
y = 0;
MySqlDataAdapter da;
if (val == false)
{
da = new MySqlDataAdapter("select * from " + folder + "", conn);
}
else
{
da = new MySqlDataAdapter("select * from " + folder + " where abc= '" + colName + "'", conn);
}
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataColumn coloumn in dt.Columns)
{
if (!coloumn.ColumnName.Equals("emp"))
{
var linkF = new TemplateField();
linkF.HeaderText = coloumn.ColumnName;
linkF.HeaderTemplate = new LinkColumn(ListItemType.Header, coloumn.ColumnName,folder);
linkF.ItemTemplate = new LinkColumn(ListItemType.Item, coloumn.ColumnName,folder);
GridView1.Columns.Add(linkF);
}
else if (coloumn.ColumnName.Equals("emp"))
{
//Response.Write("Came");
BoundField bfield = new BoundField();
////Initalize the DataField value.
bfield.DataField = coloumn.ColumnName;
////Initialize the HeaderText field value.
bfield.HeaderText = coloumn.ColumnName;
GridView1.Columns.Add(bfield);
}
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
class LinkColumn : DetailView, ITemplate
{
int id;
ListItemType _item;
String colN = null;
String fold;
public LinkColumn(ListItemType item, String colNa, String f)
{
_item = item;
colN = colNa;
fold = f;
}
public void InstantiateIn(System.Web.UI.Control container)
{
switch (_item)
{
case ListItemType.Header:
DetailView.dp = new DropDownList();
Label lb = new Label();
MySqlCommand cm = new MySqlCommand("select distinct " + colN + " from " + fold + "", conn);
MySqlDataAdapter ad = new MySqlDataAdapter();
DataTable d = new DataTable();
ad.SelectCommand = cm;
ad.Fill(d);
DetailView.dp.DataTextField = colN;
DetailView.dp.DataValueField = colN;
DetailView.dp.DataSource = d;
DetailView.dp.DataBind();
lb.Text = colN.ToUpperInvariant();
dp.AutoPostBack = true;
dp.EnableViewState = true;
// DetailView.dp.ID = y.ToString();
y++;
container.Controls.Add(lb);
container.Controls.Add(DetailView.dp);
// DetailView.dp.ID = DetailView.y.ToString();
// Response.Write(_Default.dp.ID);
DetailView.dp.SelectedIndexChanged += new EventHandler(dp_Selected);
break;
case ListItemType.Item:
TextBox tb1 = new TextBox();
tb1.Enabled = false;
tb1.DataBinding += new EventHandler(tb1_Data);
tb1.Columns = 30;
container.Controls.Add(tb1);
break;
}
}
void tb1_Data(object sender, EventArgs e)
{
TextBox txt = (TextBox)sender;
GridViewRow cont = (GridViewRow)txt.NamingContainer;
object dataV = DataBinder.Eval(cont.DataItem, colN);
if (dataV != DBNull.Value)
{
txt.Text = dataV.ToString();
}
}
void dp_Selected(object sender, EventArgs e)
{
DataTable a = new DataTable();
DropDownList list = (DropDownList)sender;
String name = list.SelectedValue;
// String ID = list.ID.ToString();
// Session["id"] = ID;
Session["cols"] = name;
DetailView.colName = Session["cols"].ToString();
DetailView.flag = true;
// Response.Write(DetailView.colName);
GridBind(fold, DetailView.colName, true);
}
}
}
When i am calling GridBind function from event handler it is giving Null pointer Excpetion at GridView1.DataSource = null;
My GridView1 is present in DetailView.aspx
}
Any help be highly appreciated
Thanks

Categories

Resources