GridView is not binding C# - c#

I am using GridView and trying to bind data to this GridView, but I am facing unusual problem, here is my code :
Method to bind GridView :
private void BindDataSource()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString);
string queryString6 = "";
string items = "";
if (lb_add_col.Items.Count > 0)
{
foreach (ListItem listItem in lb_add_col.Items)
{
if (listItem.Selected == true)
{
items += listItem.Text + ",";
}
}
}
items = items.TrimEnd(',');
queryString6 = "SELECT "+items+" from " +ddl_tables.Items[0].Text;
System.Data.SqlClient.SqlCommand sqlCmd6 = new System.Data.SqlClient.SqlCommand(queryString6, con);
System.Data.SqlClient.SqlDataAdapter dataAdapter6 = new System.Data.SqlClient.SqlDataAdapter(sqlCmd6);
System.Data.DataSet dataSet6 = new System.Data.DataSet();
dataAdapter6.Fill(dataSet6);
string[] columns = items.Split(',');
for (int i = 0; i < dataSet6.Tables[0].Rows.Count; i++)
{
order.Add(new Orders(columns.Contains("id") ? Convert.ToInt32(dataSet6.Tables[0].Rows[i]["id"]) : 0, columns.Contains("name") ? dataSet6.Tables
[0].Rows[i]["name"].ToString() : "N/A", columns.Contains("month") ? dataSet6.Tables[0].Rows[i]["month"].ToString() : "N/A", columns.Contains("effiecency") ? Convert.ToInt32(dataSet6.Tables[0].Rows[i]
["effiecency"]) : 0, columns.Contains("latitude") ? Convert.ToInt32(dataSet6.Tables[0].Rows[i]["latitude"]) : 0, columns.Contains("longitude") ? Convert.ToInt32(dataSet6.Tables[0].Rows[i]
["longitude"]) : 0));
}
this.OrdersGrid.DataSource = order;
this.OrdersGrid.DataBind();
}
From above method order is showing the data but GridView is not binding.
Button Click event on which I am calling this method :
protected void btn_add_col_Click(object sender, EventArgs e)
{
Syncfusion.JavaScript.Models.Column sd;
foreach (ListItem listItem in lb_add_col.Items)
{
if (listItem.Selected == true)
{
sd = new Syncfusion.JavaScript.Models.Column();
if (listItem.Text == "id")
{
sd.IsPrimaryKey = true;
}
sd.Field = listItem.Text;
sd.HeaderText = listItem.Value;
sd.Width = 90;
sd.TextAlign = Syncfusion.JavaScript.TextAlign.Right;
this.OrdersGrid.Columns.Add(sd);
}
}
BindDataSource();
}

If the order contains value after the loop has executed then the data source will be bind to the Grid. But the Grid does not contain the columns that you have defined in the button click, it return all columns in the grid data source. the Grid has only shown the column that you have define in the bindDataSource method,

if dataSet6.Tables[0].Rows.Count is zero, the GridView will databind but there will be no data.

Related

Execute Method (that updating datagridview) from Another Form C#

I have 2 form. MainPage form contains datagridview and fetchTradeReport method to populate/refresh datagrid, while ColumnSettings form use to configure which datagridviewcolumn that user want to be visible or not. I have "Apply Changes" button in ColumnSettings form, and I include fetchTradeReport method in the click event. But, the datagrid still the same and don't change after I clicked it.
This is my fetchTradeReport method
public void fetchTradeReport()
{
try
{
TTransport transport = new TSocket(address, port);
TProtocol protocol = new TBinaryProtocol(transport);
CacheService.Client client = new CacheService.Client(protocol);
transport.Open();
List<string> transactTime = new List<string>();
SearchCriteria criteria = new SearchCriteria();
criteria.Filters = new List<Filter>();
DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
if (Convert.ToString(tradeStatusCB.Text) != "")
setTradeStatusFilter(criteria, (TradeReportStatus)Enum.Parse(typeof(TradeReportStatus), Convert.ToString(tradeStatusCB.Text)));
if (platformTB.Text != "")
setPlatformFilter(criteria, platformTB.Text);
if (exchangeTB.Text != "")
criteria.Exchange = exchangeTB.Text;
if (productTB.Text != "")
criteria.Product = productTB.Text;
if (accountTB.Text != "")
criteria.Account = accountTB.Text;
if (orderidTB.Text != "")
setOrderIDFilter(criteria, orderidTB.Text);
if (tradereportidTB.Text != "")
setReportIDFilter(criteria, tradereportidTB.Text);
if (tradedateDTP.Text.Length != 1)
criteria.TradeDate = Convert.ToInt32(tradedateDTP.Value.ToString("yyyyMMdd"));
var tradeList = client.getTradeReports(criteria);
tradeGridView.DataSource = tradeList;
foreach (DataGridViewRow row in tradeGridView.Rows)
{
double time = Convert.ToDouble(row.Cells["TransactTime"].Value);
string dtm = dt.AddSeconds(time).ToLocalTime().ToString();
transactTime.Add(dtm);
}
tradeGridView.Columns.Remove("TransactTime");
if(tradeGridView.Columns.Contains("TransactionTime"))
tradeGridView.Columns.Remove("TransactionTime");
tradeGridView.Columns.Add("TransactionTime", "TransactionTime");
tradeGridView.Columns["TransactionTime"].ValueType = typeof(String);
int i = 0;
foreach (DataGridViewRow row in tradeGridView.Rows)
{
row.Cells["TransactionTime"].Value = transactTime[i];
i++;
}
int counter = 0;
string line;
if (File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + #"\\ColumnSettings.config"))
{
StreamReader readFile = new StreamReader(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + #"\\ColumnSettings.config");
while ((line = readFile.ReadLine()) != null)
{
string columnName = line.Substring(0, line.Length - 2);
tradeGridView.Columns[columnName].DisplayIndex = counter;
if (line.Split('-').Last() == "1")
tradeGridView.Columns[columnName].Visible = true;
else
tradeGridView.Columns[columnName].Visible = false;
counter++;
}
readFile.Close();
}
else
collectColumnName();
transport.Close();
}
catch (Exception e)
{
MessageBox.Show(e.StackTrace);
}
}
And this is how I call it in "Apply Changes" button click event in ColumnSettings form
new MainPage(GetConnectionString.address, GetConnectionString.port).fetchTradeReport();
Sorry if my English bad. Any help appreciated. Thanks.

Gridview Footer Default Value Missing

I have a gridview which can searched by date.
In the gridview, i manually add in footer if the gridview for the date is empty.
It work fine then first load the page.
The problem is :
When load the gridview with data, the footer show default data. After that, select date where no data, default values are missing. If I select another date without data, the default value of footer come out again.
I put breakpoint and it went through the following function, the value is not null but it is no displayed on the Label of footer.
while (Dr.Read())
{
AttendbyFooter.Text = Dr.GetValue(1).ToString();
DepartmentFooter.Text = Dr.GetValue(4).ToString();
}
Gridview databound:
Label AttendbyFooter = GridView1.FooterRow.FindControl("AttendbyFooter") as Label;
//if the footer is null, do nothing. if the footer is not null, continue for other value
if (AttendbyFooter == null)
{
}
else
{
//set default name
AttendbyFooter.Attributes.Add("readonly", "readonly");
Label DepartmentFooter = GridView1.FooterRow.FindControl("DepartmentFooter") as Label;
DepartmentFooter.Attributes.Add("readonly", "readonly");
//create a connection to mssql server
var Cn = new System.Data.SqlClient.SqlConnection();
Cn.ConnectionString = ConfigurationManager.ConnectionStrings["CMOSConnectionString"].ConnectionString;
Cn.Open();
//create a command object from the connection
var Cm = Cn.CreateCommand();
//Check database using username(id number)
Cm.CommandText = string.Format(#"Select * From Employee WHERE PassNumber='{0}'", User.Identity.Name);
var Dr = Cm.ExecuteReader();
while (Dr.Read())
{
//Name
AttendbyFooter.Text = Dr.GetValue(1).ToString();
DepartmentFooter.Text = Dr.GetValue(4).ToString();
}
Cn.Close();
}
Generate footer(copy from website)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace YourNamespace
{
public class GridViewExtended : GridView
{
#region Public Properties
[Category("Behavior")]
[Themeable(true)]
[Bindable(BindableSupport.No)]
public bool ShowFooterWhenEmpty
{
get
{
if (this.ViewState["ShowFooterWhenEmpty"] == null)
{
this.ViewState["ShowFooterWhenEmpty"] = false;
}
return (bool)this.ViewState["ShowFooterWhenEmpty"];
}
set
{
this.ViewState["ShowFooterWhenEmpty"] = value;
}
}
#endregion
private GridViewRow _footerRow2;
public override GridViewRow FooterRow
{
get
{
GridViewRow f = base.FooterRow;
if (f != null)
return f;
else
return _footerRow2;
}
}
protected override int CreateChildControls(System.Collections.IEnumerable dataSource, bool dataBinding)
{
int rows = base.CreateChildControls(dataSource, dataBinding);
// no data rows created, create empty table if enabled
if (rows == 0 && (this.ShowFooterWhenEmpty))
{
// create the table
Table table = this.CreateChildTable();
DataControlField[] fields;
if (this.AutoGenerateColumns)
{
PagedDataSource source = new PagedDataSource();
source.DataSource = dataSource;
System.Collections.ICollection autoGeneratedColumns = this.CreateColumns(source, true);
fields = new DataControlField[autoGeneratedColumns.Count];
autoGeneratedColumns.CopyTo(fields, 0);
}
else
{
fields = new DataControlField[this.Columns.Count];
this.Columns.CopyTo(fields, 0);
}
if (this.ShowHeaderWhenEmpty)
{
// create a new header row
GridViewRow headerRow = base.CreateRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal);
this.InitializeRow(headerRow, fields);
// add the header row to the table
table.Rows.Add(headerRow);
}
// create the empty row
GridViewRow emptyRow = new GridViewRow(-1, -1, DataControlRowType.EmptyDataRow, DataControlRowState.Normal);
TableCell cell = new TableCell();
cell.ColumnSpan = fields.Length;
cell.Width = Unit.Percentage(100);
// respect the precedence order if both EmptyDataTemplate
// and EmptyDataText are both supplied ...
if (this.EmptyDataTemplate != null)
{
this.EmptyDataTemplate.InstantiateIn(cell);
}
else if (!string.IsNullOrEmpty(this.EmptyDataText))
{
cell.Controls.Add(new LiteralControl(EmptyDataText));
}
emptyRow.Cells.Add(cell);
table.Rows.Add(emptyRow);
if (this.ShowFooterWhenEmpty)
{
// create footer row
_footerRow2 = base.CreateRow(-1, -1, DataControlRowType.Footer, DataControlRowState.Normal);
this.InitializeRow(_footerRow2, fields);
// add the footer to the table
table.Rows.Add(_footerRow2);
}
this.Controls.Clear();
this.Controls.Add(table);
}
return rows;
}
}
}
Try clearing the date textbox after pageload.

Index (zero based) must be greater than or equal to zero and less than the size of the argument list while inserting the arraylist

I'm getting this error:
Index (zero based) must be greater than or equal to zero and less than the size of the argument list.
at here:
splitItems = item.Split(",".ToCharArray());
sb.AppendFormat("{0}('{1}','{2}','{3}','{4}'); ",
ds.InsertPlan("1", splitItems[0], splitItems[1], splitItems[2],
splitItems[3], DateTime.Now, DateTime.Now, user, user, "Nil", 1));
And the C# code is given below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Collections.Specialized;
using System.Text;
public partial class Site_Allocation_Plan_Entry : System.Web.UI.Page
{
private void SetInitialRowToGrid()
{
// Initialize and Set initial row of Datatable
var tempDataTable = new DataTable();
tempDataTable.Columns.Add("txtDate1");
tempDataTable.Columns.Add("txtPlace1");
tempDataTable.Columns.Add("txtPlace2");
tempDataTable.Columns.Add("txtDistance");
tempDataTable.Rows.Add("1", "", "", "");
// Store that datatable into viewstate
ViewState["TempTable"] = tempDataTable;
// Attach Gridview Datasource to datatable
GridView1.DataSource = tempDataTable;
GridView1.DataBind();
}
private void AddNewRowToGrid()
{
int rowIndex = 0;
if (ViewState["TempTable"] != null)
{
// Get TempTable from viewstate
var tempTable = (DataTable)ViewState["TempTable"];
DataRow tempRow = null;
if (tempTable.Rows.Count > 0)
{
for (int i = 1; i <= tempTable.Rows.Count; i++)
{
// Get Grid's TextBox values
var dateText =
(TextBox)GridView1.Rows[rowIndex].Cells[1].FindControl("txtDate1");
var place1Text =
(TextBox)GridView1.Rows[rowIndex].Cells[1].FindControl("txtPlace1");
var place2Text =
(TextBox)GridView1.Rows[rowIndex].Cells[1].FindControl("txtPlace2");
var distanceText =
(TextBox)GridView1.Rows[rowIndex].Cells[1].FindControl("txtDistance");
// Create new row and update Row Number
tempRow = tempTable.NewRow();
tempTable.Rows[i - 1]["txtDate1"] = dateText.Text;
tempTable.Rows[i - 1]["txtPlace1"] = place1Text.Text;
tempTable.Rows[i - 1]["txtPlace2"] = place2Text.Text;
tempTable.Rows[i - 1]["txtDistance"] = distanceText.Text;
rowIndex++;
}
// Add data to datatable and viewstate
tempTable.Rows.Add(tempRow);
ViewState["TempTable"] = tempTable;
// Attach Gridview Datasource to datatable
GridView1.DataSource = tempTable;
GridView1.DataBind();
}
}
//Set Previous Data on Postbacks
SetPreviousData();
}
private void SetPreviousData()
{
int rowIndex = 0;
if (ViewState["TempTable"] != null)
{
var tempTable = (DataTable)ViewState["TempTable"];
if (tempTable.Rows.Count > 0)
{
for (int i = 0; i < tempTable.Rows.Count; i++)
{
var dateText =
(TextBox)GridView1.Rows[rowIndex].Cells[1].FindControl("txtDate1");
var place1Text =
(TextBox)GridView1.Rows[rowIndex].Cells[1].FindControl("txtPlace1");
var place2Text =
(TextBox)GridView1.Rows[rowIndex].Cells[2].FindControl("txtPlace2");
var distanceText =
(TextBox)GridView1.Rows[rowIndex].Cells[3].FindControl("txtDistance");
dateText.Text = tempTable.Rows[i]["txtDate1"].ToString();
place1Text.Text = tempTable.Rows[i]["txtPlace1"].ToString();
place2Text.Text = tempTable.Rows[i]["txtPlace2"].ToString();
distanceText.Text = tempTable.Rows[i]["txtDistance"].ToString();
rowIndex++;
}
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.SetInitialRowToGrid();
}
}
protected void ButtonAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int index = Convert.ToInt32(e.RowIndex);
deleteRow(index);
SetPreviousData();
}
private int deleteRow(int index)
{
int rowIndex = 0;
if (ViewState["TempTable"] != null)
{
// Get TempTable from viewstate
var tempTable = (DataTable)ViewState["TempTable"];
if (tempTable.Rows.Count > 0)
{
for (int i = 1; i <= tempTable.Rows.Count; i++)
{
// Get Grid's TextBox values
var dateText =
(TextBox)GridView1.Rows[rowIndex].Cells[1].FindControl("txtDate1");
var place1Text =
(TextBox)GridView1.Rows[rowIndex].Cells[1].FindControl("txtPlace1");
var place2Text =
(TextBox)GridView1.Rows[rowIndex].Cells[1].FindControl("txtPlace2");
var distanceText =
(TextBox)GridView1.Rows[rowIndex].Cells[1].FindControl("txtDistance");
}
// Add data to datatable and viewstate
tempTable.Rows.RemoveAt(index);
ViewState["TempTable"] = tempTable;
// Attach Gridview Datasource to datatable
GridView1.DataSource = tempTable;
GridView1.DataBind();
}
}
//Set Previous Data on Postbacks
return index;
}
protected void btnSave_Click(object sender, EventArgs e)
{
int rowIndex = 0;
StringCollection sc = new StringCollection();
if (ViewState["TempTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["TempTable"];
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
//extract the TextBox values
TextBox box1 = (TextBox)GridView1.Rows[rowIndex].Cells[1].FindControl("txtPlace1");
TextBox box2 = (TextBox)GridView1.Rows[rowIndex].Cells[2].FindControl("txtPlace2");
TextBox box3 = (TextBox)GridView1.Rows[rowIndex].Cells[3].FindControl("txtDistance");
TextBox box4 = (TextBox)GridView1.Rows[rowIndex].Cells[4].FindControl("txtDate1");
//get the values from the TextBoxes
//then add it to the collections with a comma "," as the delimited values
sc.Add(box1.Text + "," + box2.Text + "," + box3.Text + "," + box4.Text);
rowIndex++;
}
//Call the method for executing inserts
InsertRecords(sc);
}
}
}
private void InsertRecords(StringCollection sc)
{
DS_SiteDataTableAdapters.tbl_planTableAdapter ds;
ds = new DS_SiteDataTableAdapters.tbl_planTableAdapter();
StringBuilder sb = new StringBuilder(string.Empty);
string[] splitItems = null;
string user = Page.User.Identity.Name;
foreach (string item in sc)
{
if (item.Contains(","))
{
splitItems = item.Split(",".ToCharArray());
sb.AppendFormat("{0}('{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}'); ", ds.InsertPlan("1", splitItems[0], splitItems[1], splitItems[2], splitItems[3], DateTime.Now, DateTime.Now, user, user, "Nil", 1));
}
}
try
{
//Display a popup which indicates that the record was successfully inserted
Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('Records Successfuly Saved!');", true);
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
}
}
Any help will be greatly appreciated...
Your sb.AppendFormat format string expects 5 items.
You said ds.InsertPlan() has the following signature, and the arguments map to InsertPlan() not AppendFormat(). However, InsertPlan() returns a single int, so AppendFormat() only has 1 argument, an int value.
public virtual int InsertPlan(
string Plan_ID, <- "1"
string Place_1, <- splitItems[0]
string Place_2, <- splitItems[1]
string Distance, <- splitItems[2]
string Date, <- splitItems[3]
System.Nullable<System.DateTime> Created_Time, <- DateTime.Now
System.Nullable<System.DateTime> Updated_Time, <- DateTime.Now
string Created_by, <- user
string Updated_By, <- user
string Version_Status, <- "Nil"
System.Nullable<int> p3 <- 1
)
Your code:
sb.AppendFormat("{0}('{1}','{2}','{3}','{4}'); ",
ds.InsertPlan("1", // <-- unless InsertPlan() returns an array, then this
// is only 1 argument to the outer function
splitItems[0],
splitItems[1],
splitItems[2],
splitItems[3],
DateTime.Now, DateTime.Now, user, user, "Nil", 1
)
);
is like:
sb.AppendFormat("{0}('{1}','{2}','{3}','{4}'); ",
1); // only {0} has a argument
// {1} ... {4} do not

Dynamic Report building Refresh() is not changing data

I am trying to View a report dynamically from code behind. But when the parameters are changed from dynamic textboxes added in the page. in the report refresh() the data is not changed.
I call sqlDS() and reportBuild() in the !IsPostback.
This method is for defining the sqlDatasource:
protected void sqlDS()
{
string conString, prName = "";
int counter = 0;
Reporting rep = new Reporting();
rep = rep.searchReport(repID_HF.Value);
Reporting repFold = new Reporting();
repFold = repFold.searchFolder(foldID_HF.Value);
if (repFold.FolderName.Split('(')[1] == "Web Reports)")
{
conString = dbSql.connectionStringAll;
prName = dbSql.providerName;
}
else
{
conString = db.connectionStringAll;
prName = db.providerName;
}
SqlDataSource1.ConnectionString = conString;
SqlDataSource1.ProviderName = prName;
string sqlString = System.IO.File.ReadAllText(Server.MapPath("~/Reports/SQLs/" + rep.SqlFile));
sqlString.Replace(System.Environment.NewLine, " ");
SqlDataSource1.SelectCommand = sqlString;
SqlDataSource1.CancelSelectOnNullParameter = false;
Reporting repParam = new Reporting();
allPs = repParam.getAllParamRep(rep.RepID);
foreach (Reporting itemParam in allPs)
{
if (itemParam.ParamType == "Date")
{
SqlDataSource1.SelectParameters.Add(":" + itemParam.ParamName, itemParam.ParamDefaultValue);
counter++;
}
else if (itemParam.ParamType == "Text")
{
SqlDataSource1.SelectParameters.Add(":" + itemParam.ParamName, itemParam.ParamDefaultValue);
counter++;
}
else if (itemParam.ParamType == "Menu")
{
counter++;
}
}
}
This method is for declaring the report properties:
protected void reportBuild()
{
Reporting rep2 = new Reporting();
rep2 = rep2.searchReport(repID_HF.Value);
ReportViewer1.LocalReport.ReportPath = "Reports/RDLC/" + rep2.RdlcFile;
this.ReportViewer1.LocalReport.ReportEmbeddedResource = rep2.RdlcFile;
ReportParameter[] paramss = new ReportParameter[SqlDataSource1.SelectParameters.Count];
for (int i = 0; i < SqlDataSource1.SelectParameters.Count; i++)
{
paramss[i] = new ReportParameter(SqlDataSource1.SelectParameters[i].Name.Split(':')[1], SqlDataSource1.SelectParameters[i].DefaultValue);
}
ReportDataSource rds = new ReportDataSource(rep2.DatasetName.Split('.')[0], SqlDataSource1);
ReportViewer1.LocalReport.DataSources.Clear();
ReportViewer1.LocalReport.DataSources.Add(rds);
//paramss[0] = new ReportParameter("TDATE", SqlDataSource1.SelectParameters[0].DefaultValue);
//paramss[1] = new ReportParameter("CUST_NUM", SqlDataSource1.SelectParameters[1].DefaultValue);
ReportViewer1.LocalReport.SetParameters(paramss);
ReportViewer1.LocalReport.Refresh();
}
In the reportViewer refresh method i try to set the new parameters according to the dynamic textboxes added in the page:
protected void ReportViewer1_ReportRefresh(object sender, System.ComponentModel.CancelEventArgs e)
{
foreach (Control txt in Panel1.Controls)
{
if (txt is TextBox)
{
txts.Add(txt);
}
}
foreach (TextBox txtbox in txts)
{
Reporting repP = new Reporting();
repP = repP.searchParam(txtbox.Attributes["pID"].ToString());
if (repP.ParamType == "Date")
{
SqlDataSource1.SelectParameters[":" + repP.ParamName].DefaultValue = txtbox.Text;
}
else if (repP.ParamType == "Text")
{
SqlDataSource1.SelectParameters[":" + repP.ParamName].DefaultValue = txtbox.Text;
}
}
//Reporting r = new Reporting();
//r = r.searchReport(repID_HF.Value);
//Reporting rep = new Reporting();
//rep = rep.searchReport(repID_HF.Value);
//ReportDataSource rds = new ReportDataSource(rep.DatasetName.Split('.')[0], SqlDataSource1);
//this.ReportViewer1.Reset();
//ReportViewer1.LocalReport.DataSources.Clear();
//ReportViewer1.LocalReport.DataSources.Add(rds);
ReportParameterInfoCollection x = ReportViewer1.LocalReport.GetParameters();
//Response.Redirect(Request.RawUrl);
ReportViewer1.LocalReport.Refresh();
}
I tried debugging and found every thing is working correctly the SQL parameters changed, the Report Parameters also is changed.
so why the data in the report is not changed? Plz help me
I got a better and easier way to solve this problem using this link
http://www.igregor.net/post/2007/12/Adding-Controls-to-an-ASPNET-form-Dynamically.aspx
And you can use array of strings to pass attributes.

how to set SelectedIndex in DataGridViewComboBoxColumn?

i am using a datagridview in that i am using a datagridviewcomboboxcolumn, comboboxcolumn is displaying text but the problem is i want to select the first item of comboboxcolumn by default how can i do this
DataGridViewComboBoxColumn dgvcb = (DataGridViewComboBoxColumn)grvPackingList.Columns["PackingUnits"];
Globals.G_ProductUtility G_Utility = new Globals.G_ProductUtility();
G_Utility.addUnittoComboDGV(dgvcb);
DataSet _ds = iRawMaterialsRequest.SelectBMR(bmr_ID, branch_ID, "PACKING");
grvPackingList.DataSource = _ds.Tables[0];
int i = 0;
foreach (DataRow dgvr in _ds.Tables[0].Rows)
{
grvPackingList.Rows[i].Cells["Units"].Value = dgvr["Units"].ToString();
i++;
}
The values available in the combobox can be accessed via items property
row.Cells[col.Name].Value = (row.Cells[col.Name] as DataGridViewComboBoxCell).Items[0];
the best way to set the value of a datagridViewComboBoxCell is:
DataTable dt = new DataTable();
dt.Columns.Add("Item");
dt.Columns.Add("Value");
dt.Rows.Add("Item1", "0");
dt.Rows.Add("Item1", "1");
dt.Rows.Add("Item1", "2");
dt.Rows.Add("Item1", "3");
DataGridViewComboBoxColumn cmb = new DataGridViewComboBoxColumn();
cmb.DefaultCellStyle.Font = new Font("Tahoma", 8, FontStyle.Bold);
cmb.DefaultCellStyle.ForeColor = Color.BlueViolet;
cmb.FlatStyle = FlatStyle.Flat;
cmb.Name = "ComboColumnSample";
cmb.HeaderText = "ComboColumnSample";
cmb.DisplayMember = "Item";
cmb.ValueMember = "Value";
DatagridView dvg=new DataGridView();
dvg.Columns.Add(cmb);
cmb.DataSource = dt;
for (int i = 0; i < dvg.Rows.Count; i++)
{
dvg.Rows[i].Cells["ComboColumnSample"].Value = (cmb.Items[0] as
DataRowView).Row[1].ToString();
}
It worked with me very well
If I had known about doing it in this event, it would have saved me days of digging and
trial and errors trying to get it to set to the correct index inside the CellEnter event.
Setting the index of the DataGridViewComboBox is the solution I have been looking for.....THANKS!!!
In reviewing all the issues other coders have been experiencing with trying to set
the index inside of a DataGridViewComboBoxCell and also after looking over your code,
all that anyone really needs is:
1. Establish the event method to be used for the "EditingControlShowing" event.
2. Define the method whereby it will:
a. Cast the event control to a ComboBox.
b. set the "SelectedIndex" to the value you want.
In this example I simply set it to "0", but you'd probably want to apply so real life logic here.
Here's the code I used:
private void InitEvents()
{
dgv4.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler( dgv4EditingControlShowing );
}
private void dgv4EditingControlShowing( object sender, DataGridViewEditingControlShowingEventArgs e )
{
ComboBox ocmb = e.Control as ComboBox;
if ( ocmb != null )
{
ocmb.SelectedIndex = 0;
}
}
If DataGridViewComboBoxCell already exist:
DataTable dt = new DataTable();
dt.Columns.Add("Item");
dt.Columns.Add("Value");
dt.Rows.Add("Item 1", "0");
dt.Rows.Add("Item 2", "1");
dt.Rows.Add("Item 3", "2");
dt.Rows.Add("Item 4", "3");
for (int i = 0; i < dvg.Rows.Count; i++)
{
DataGridViewComboBoxCell comboCell = (DataGridViewComboBoxCell)dvg.Rows[i].Cells[1];
comboCell.DisplayMember = "Item";
comboCell.ValueMember = "Value";
comboCell.DataSource = dt;
};
I've had some real trouble with ComboBoxes in DataGridViews and did not find an elegant way to select the first value. However, here is what I ended up with:
public static void InitDGVComboBoxColumn<T>(DataGridViewComboBoxCell cbx, List<T> dataSource, String displayMember, String valueMember)
{
cbx.DisplayMember = displayMember;
cbx.ValueMember = valueMember;
cbx.DataSource = dataSource;
if (cbx.Value == null)
{
if(dataSource.Count > 0)
{
T m = (T)cbx.Items[0];
FieldInfo fi = m.GetType().GetField(valueMember, BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);
cbx.Value = fi.GetValue(m);
}
}
}
It basically sets the .Display and .ValueMember properties of the DataGridViewComboBoxCell and uses a List as DataSource. It then takes the first item, and uses reflection to get the value of the member that was used as ValueMember and sets the selected value via .Value
Use it like this:
public class Customer
{
private String name;
public String Name
{
get {return this.name; }
set {this.name = value; }
}
private int id;
public int Id
{
get {return this.id; }
set {this.id = value; }
}
}
public class CustomerCbx
{
private String display;
public String Display
{
get {return this.display; }
set {this.display = value; }
}
private Customer value;
public Customer Value
{
get {return this.value; }
set {this.value = value; }
}
}
public class Form{
private void Form_OnLoad(object sender, EventArgs e)
{
//init first row in the dgv
if (this.dgv.RowCount > 0)
{
DataGridViewRow row = this.dgv.Rows[0];
DataGridViewComboBoxCell cbx = (DataGridViewComboBoxCell)row.Cells[0];
Customer c1 = new Customer(){ Name = "Max Muster", ID=1 };
Customer c2 = new Customer(){ Name = "Peter Parker", ID=2 };
List<CustomerCbx> custList = new List<CustomerCbx>()
{
new CustomerCbx{ Display = c1.Name, Value = c1},
new CustomerCbx{ Display = c2.Name, Value = c2},
}
InitDGVComboBoxColumn<CustomerCbx>(cbx, custList, "display", "value");
}
}
}
}
It seems pretty hacky to me, but I couldn't find any better way so far (that also works with complex objects other than just Strings). Hope that will save the search for some others ;)
You need to set the Items for the new cell. This must be auto done by the column when creating a new row from the UI.
var cell = new DataGridViewComboBoxCell() { Value = "SomeText" };
cell.Items.AddRange(new String[]{"SomeText", "Abcd", "123"});
something different worked for me what i did is to simply set the value of dtataGridComboBox when ever new record is added bu user with 'userAddedRow' event. For the first row I used the code in constructor.
public partial class pt_drug : PatientDatabase1_3._5.basic_templet
{
public pt_drug()
{
InitializeComponent();
dataGridView_drugsDM.Rows[0].Cells[0].Value = "Tablet";
}
private void dataGridView_drugsDM_UserAddedRow(object sender, DataGridViewRowEventArgs e)
{
dataGridView_drugsDM.Rows[dataGridView_drugsDM.RowCount - 1].Cells[0].Value = "Tablet";
}
}
Here the solution I have found : select the cell you are interested in so you can cast it to a combobox.
this.Invoke((MethodInvoker)delegate
{
this.dataGridView1.CurrentCell = dataGridView1.Rows[yourRowindex].Cells[yourColumnIndex];
this.dataGridView1.BeginEdit(true);
ComboBox comboBox = (ComboBox)this.dataGridView1.EditingControl;
comboBox.SelectedIndex += 1;
});

Categories