Asp.net Gridview Rowdata is coming empty and Unchecked - c#

I have a requirement where i need to add column names and rowdatabound values dynamically .I has managed to get Column names dynamically .According to my need i want values to be displayed in the form of checkboxes in the rows of the grid either in checked form or unchecked based on condition but here every thing is coming in unchecked formate ..
I am using .net membership Role table...
Here is my code for gridview Dynamic column allocation..
protected void BindGridviewData()
{
var role = from MembershipUser u in Membership.GetAllUsers()
select new
{
User = u.UserName,
Role = string.Join(",", Roles.GetRolesForUser(u.UserName))
};
DataTable dTable = new DataTable();
string[] rolesarr = Roles.GetAllRoles();
// add column for user name
dTable.Columns.Add("Username", typeof(string));
// then add all the roles as columns
Array.ForEach(rolesarr, r => dTable.Columns.Add(r));
List<string> tempfield = new List<string>();
foreach (DataColumn column in dTable.Columns)
{
string ColName = column.ColumnName;
tempfield.Add(ColName);
}
for (int i = 0; i < tempfield.Count; i++)
{
string tempfieldname = tempfield[i];
TemplateField temp = new TemplateField();
if (i == 0)
{
temp.HeaderText = tempfieldname;
tempfieldname = string.Empty;
}
else {
temp.ItemTemplate = new MyTemplate();
temp.HeaderText = tempfieldname;
tempfieldname = string.Empty;
}
GridView1.Columns.Add(temp);
}
Now Here i am checking values to be checked or uncked..
foreach (MembershipUser u in Membership.GetAllUsers())
{
DataRow dRow = dTable.NewRow();
dRow[0] = u.UserName;
string[] roles = Roles.GetRolesForUser(u.UserName);
dRow[1] = roles.Contains("Admin") ? true : false;
dRow[2] = roles.Contains("DPAO User") ? true : false;
dRow[3] = roles.Contains("GeneralUser") ? true : false;
dTable.Rows.Add(dRow);
}
GridView1.DataSource = dTable;
GridView1.DataBind();
}
Upto here values are coming fine in dTable but once flow goes to rowdatabound event
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
}
On rowdatabound event flow automatically moves to custom control class which is ...
public class MyTemplate : ITemplate
{
public void InstantiateIn(Control container)
{
CheckBox chk = new CheckBox();
chk.ID = "chk";
container.Controls.Add(chk);
}
}
And from here all checkboxes are displaying as unchecked ...
Please guys help me ..
Thanks in advance...

Do it in this way. check where the column is true false in the rowDatabound event and the add control here only.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
CheckBox cb = new CheckBox();
if(e.Row.Cells["Column Name"].toString == true ){
cb.Checked = true;
}else{
cb.Checked = false;
}
e.Row.Cells["Column Name"].Controls.Add(cb);
}
}

Related

getting indivdul cell from DataTable from CellClickEvent

I am new to DataTables and am trying to access individual cells opposed to rows and colls. I have inseretd an array of data through the findResult
which is from an exsiting webService. I am now trying to access the 'Id' column, but the individual cell that the user will click on. I will then stored this in a var to be used for further processing within the class.
I have populated my datatable as follows:
DataTable ss = new DataTable();
ss.Columns.Add("ID");
ss.Columns.Add("Text");
ss.Columns.Add("Highlight");
ss.Columns.Add("Cursor");
ss.Columns.Add("Description");
ss.Columns.Add("Next");
DataRow row = ss.NewRow();
row["ID"] = findResults[0].Id;
row["Text"] = findResults[0].Text;
row["Highlight"] = findResults[0].Highlight;
row["Cursor"] = findResults[0].Cursor;
row["Description"] = findResults[0].Description;
row["Next"] = findResults[0].Next;
ss.Rows.Add(row);
if (txt_Search.Text.Length <= 2 || txt_Search.Text.Length >= 9)
{ MessageBox.Show("Please enter more than 2 Chars!!"); }
foreach (DataRow itemDrow in ss.Rows)
{
foreach (var item in findResults)
{
var num = dataGridView1.Rows.Add();
dataGridView1.Rows[num].Cells[0].Value = item.Id.ToString();
dataGridView1.Rows[num].Cells[1].Value = item.Text.ToString();
dataGridView1.Rows[num].Cells[2].Value = item.Highlight.ToString();
dataGridView1.Rows[num].Cells[3].Value = item.Cursor.ToString();
dataGridView1.Rows[num].Cells[4].Value = item.Description.ToString();
dataGridView1.Rows[num].Cells[5].Value = item.Next.ToString();
}
}
And this is how I have attempted to acheive my click event however it was only returning the first row and coll of the varaible 'ID' and not regestering that i had clicked on another cell.
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
string value1 = row.Cells[0].Value.ToString();
string value2 = row.Cells[1].Value.ToString();
string SerachId = findResults[0].Id.ToString();
Console.WriteLine(SerachId);
//...
}
The DataGridViewCellEventArgs in the CellClick event exposes two Properties: ColumnIndex and RowIndex which will tell you which cell the user has clicked. Once you have the DataGridViewCell getting the Value is easy.
Example:
var clickedCell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
var value = clickedCell.Value;
After having a little play around and using #Kempeths response I solved it as follows, this now prints out the information in every cell thats double clicked thanks:
public void dataGridView1_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
{
var clickedCell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
if (clickedCell != null)
{
MessageBox.Show(dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
string SerachId = clickedCell.ToString();
}

Read/edit values starting from a Telerik RadGrid

I have this situation:
... a normal RadGrid with data. And, if I clic on a row, I want to obtain this:
... a list of label-textbox pair (please pay attention: these list of data are obtained from the row, but are not part of it).
With the first RadGrid it's all okay.
Therefore, I have used a simple HTML Table for the list of pair (in the second image). This list being generated code-behind, from database.
The problem is the update of the TextBoxs: if I edit these textboxes and do clic on the Update Botton, starts the myRadGrid_UpdateCommand method. But I can't find a way to manage these textboxes (they don't appear in myRadGrid.Controls or else).
So I have tried to use another RadGrid inside the first RadGrid, but with no luck... Maybe I have to use another different Telerik control?
Someone know how I can do this?
This is part of my implementation:
protected void myRadGrid_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
{
this.myRadGrid.DataSource = this.dtListaDettagli;
this.dtListaDettagli.PrimaryKey = new DataColumn[] { this.dtListaDettagli.Columns["key"] };
}
protected void myRadGrid_ItemCreated(object sender, Telerik.Web.UI.GridItemEventArgs e)
{
if (e.Item is GridEditFormItem && e.Item.IsInEditMode)
{
GridEditFormItem item = (GridEditFormItem)e.Item;
UserControl userControl = (UserControl)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);
var listOfDetails = this.Session["listOfDetails"];
//...
var dtoTrav = (List<Detail_Type_N>) listOfDetails;
PopolaUC(dtoTrav, userControl, e.Item.ItemIndex);
}
}
private void PopolaUC<T>(List<T> data, UserControl uc, int index) where T : FlussiBaseDto
{
// ...
RadPane radPane = uc.FindControl("RadPane1") as RadPane;
var properties = TypeDescriptor.GetProperties(typeof(Detail_Type_N));
// ...
var dettaglioSelected = (from x in data
where x.IdFlusso == idFlussoSelected && x.ProgDettaglio == progDettaglioSelected
select x).FirstOrDefault();
HtmlTable htmlTable = new HtmlTable();
htmlTable.ID = "DettaglioSinistro";
var tRow = new HtmlTableRow();
int i = 0;
foreach (PropertyDescriptor prop in properties)
{
i++;
if (i > 3) // organizza la sottotabella in 2 colonne
{
tRow = new HtmlTableRow();
i = 1;
}
// Set label:
HtmlTableCell tLabel = new HtmlTableCell();
var stringInNormalCase = Regex.Replace(prop.Name, "(\\B[A-Z])", " $1");
tLabel.InnerText = stringInNormalCase;
tRow.Cells.Add(tLabel);
// Set TextBox:
HtmlTableCell tCell = new HtmlTableCell();
// ...
TextBox box = new TextBox();
box.Text = Convert.ToString(prop.GetValue(detailSelected));
box.ID = string.Format("my_{0}", prop.Name);
tCell.Controls.Add(box);
tRow.Cells.Add(tCell);
htmlTable.Rows.Add(tRow);
}
radPane.Controls.Add(htmlTable);
}
protected void myRadGrid_UpdateCommand(object source, GridCommandEventArgs e)
{
GridEditableItem editedItem = e.Item as GridEditableItem;
UserControl userControl = (UserControl)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);
//Prepare new row to add it in the DataSource
DataRow[] changedRows = this.dtListaDettagli.Select("key = " + editedItem.OwnerTableView.DataKeyValues[editedItem.ItemIndex]["key"]);
// ... and then?
catch (Exception ex)
{
changedRows[0].CancelEdit();
Label lblError = new Label();
lblError.Text = string.Format("Errore nell'aggiornamento movimento. Errore: {0} ", ex.Message);
lblError.ForeColor = System.Drawing.Color.Red;
RadGridIpa.Controls.Add(lblError);
e.Canceled = true;
}
}
You cannot generate TextBoxes and Labels dynamically.
Instead, you want to use Edit Form.
For example,
<telerik:RadGrid ID="RadGrid1" ...>
<MasterTableView>
...
<EditFormSettings>
Place those textboxes and lables here.
</EditFormSettings>
</MasterTableView>
</telerik:RadGrid>

C# Winforms datagridview: readonly in combination with allowUserToAddRows

I have a Winforms datagridview where the existing rows shouldn't be editable but the new row should be.
So i set the ReadOnly property to true on the grid, but then i still see the new row but can't edit it.
How can i combine these two properties ?
EDIT: just tried to set ReadOnly to true, but still can't edit or add new rows.
conn = new SqlCeConnection();
conn.ConnectionString = connectionstring;
conn.Open();
daFacturen = new SqlCeDataAdapter("SELECT * FROM Factuur", conn);
daFacturen.Fill(dsKlantenBeheer, "tblFactuur");
daFactuurRegels = new SqlCeDataAdapter("SELECT * FROM Factuurregel", conn);
daFactuurRegels.Fill(dsKlantenBeheer, "tblFactuurregel");
// Relation between customers and orders
DataRelation relKlantFactuur;
DataColumn relKlantFactuurcolMaster;
DataColumn relKlantFactuurcolDetail;
relKlantFactuurcolMaster = dsKlantenBeheer.Tables["tblKlant"].Columns["ID"];
relKlantFactuurcolDetail = dsKlantenBeheer.Tables["tblFactuur"].Columns["KlantID"];
relKlantFactuur = new DataRelation("RelKlantFactuur", relKlantFactuurcolMaster, relKlantFactuurcolDetail);
dsKlantenBeheer.Relations.Add(relKlantFactuur);
DataRelation relFactFactregel;
DataColumn relFactFactregelcolMaster;
DataColumn relFactFactregelcolDetail;
relFactFactregelcolMaster = dsKlantenBeheer.Tables["tblFactuur"].Columns["ID"];
relFactFactregelcolDetail = dsKlantenBeheer.Tables["tblFactuurregel"].Columns["FactuurID"];
relFactFactregel = new DataRelation("relFactFactregel", relFactFactregelcolMaster, relFactFactregelcolDetail);
dsKlantenBeheer.Relations.Add(relFactFactregel);
DataViewManager dsView = dsKlantenBeheer.DefaultViewManager;
dsView.DataViewSettings["tblKlant"].RowFilter = "Status = 0 or Status is null";
dsView.DataViewSettings["tblKlant"].Sort = "Naam, Voornaam";
// Grid Databinding
dgvFacturen.DataSource = dsView;
dgvFacturen.DataMember = "tblKlant.relKlantFactuur";
dgvFacturen.ReadOnly = true;
dgvFacturen.allowUserToAddRows = true;
Set ReadOnly for row/cells only, not for whole grid:
var row = dataGridView1.Rows[0];
row.ReadOnly = true; //whole row can't be edited
or
var row = dataGridView1.Rows[0];
row.Cells[0].ReadOnly = true; //only first cell is not editable
When DataGridView is ReadOnly then you can't edit, add, delete any row/cell in grid.
Here is my solution, simply add some custom code to CellBeginEdit, like this:
public bool Editable {get;set;}
int i;
private void dataGridView_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
if(Editable) return;
if(i == e.RowIndex)
{
foreach (DataGridViewCell cell in dataGridView1.Rows[e.RowIndex].Cells)
{
if (cell.Value == null)
{
return;
}
}
e.Cancel = true;
}
else if (dataGridView1.Rows.Count - 1 != e.RowIndex)
{
e.Cancel = true;
}
else i = e.RowIndex;
}
The code above prevent you from re-editing the new row once you input all the values for all the cells in that row. If you want to allow user to edit that new row after committing all the values, the code seems to be much simpler:
private void dataGridView_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
if(Editable) return;
if(e.RowIndex < dataGridView.Rows.Count - 2)
{
e.Cancel = true;
}
}
I've tested and works like a charm. I suppose your new row will have all the cells input with new values.

Retrieve text from dynamically created texboxes from repeater control selections

I am trying to pass the user selections from the controls generated by a repeater (checkboxes, dropdownlist, textboxes) to a datatable and use that as a data source to a gridview for testing and eventually to a stored procedure as a table variable parameter.
When there are no selections for some checkboxes, the corresponding textboxes are not generated and the code throws an exception (check to determine if the object is empty before calling the method).
The part that seems to be causing the issue is when I pass the text from the texboxes to the datatable. When I pass the checkbox names it works fine; I am trying to overcome this by checking if the text box control is generated but it still throws the same exception.
Is there a better way to check if the dynamic textbox is generated?
protected void Button2_Click(object sender, EventArgs e)
{
DataTable Frs = new DataTable("udtMParameters");
Frs.Columns.Add("MName", typeof(string));
Frs.Columns.Add("IsNum", typeof(string));
Frs.Columns.Add("MValue1", typeof(string));
Frs.Columns.Add("MValue2", typeof(string));
try
{
foreach (RepeaterItem i in Repeater1.Items)
{
CheckBox fn = i.FindControl("chk") as CheckBox;
CheckBox isn = i.FindControl("ChkboxIsNumeric") as CheckBox;
PlaceHolder plc = i.FindControl("PlcMFilter") as PlaceHolder;
TextBox s = i.FindControl("start") as TextBox;
TextBox l = i.FindControl("end") as TextBox;
DropDownList d = i.FindControl("value") as DropDownList;
if (fn.Checked)
{
TextBox1.Text = fn.Text;
if (isn.Checked)
{
DataRow dr = Frs.NewRow();
dr["MName"] = fn.Text;
dr["IsNum"] = "Y";
if (String.IsNullOrEmpty(s.Text))
{
dr["MValue1"] = s.Text;
}
else
{
dr["MValue1"] = " ";
}
if (String.IsNullOrEmpty(s.Text))
{
dr["MValue2"] = l.Text;
}
else
{
dr["MValue2"] = " ";
}
Frs.Rows.Add(dr);
}
else
{
DataRow dr = Frs.NewRow();
dr["MName"] = fn.Text;
dr["IsNum"] = "N";
dr["MValue1"] = "MValue1";
dr["MValue2"] = "MValue2";
Frs.Rows.Add(dr);
}
}
this.GridView1.Visible = true;
GridView1.DataSource = Frs;
GridView1.DataBind();
panel2.Enabled = true;
panel2.Visible = true;
}
}
catch (Exception ex)
{
throw ex;
}
}
Replace you casting realized with as by parenthesis, in order to localize your null object
TextBox s = (TextBox)i.FindControl("start");
TextBox l = (TextBox)i.FindControl("end");
On event of a conversion failure, casting with parentheses will raises an exception, while casting with as will yields a null.

how to store multiple values of checkbox values in viewstate?

here is the code for my viewstate. but it's only store one value.what i need is it will keep the selected multiple values in the checkbox. this method is to keep/hold the value of check box in gridview of paging situation.
public void chkAssignee_OnCheckedChanged(object sender, EventArgs e)
{
CheckBox selectBox = (CheckBox)sender;
GridViewRow myRow = (GridViewRow)selectBox.Parent.Parent; // the row
GridView myGrid = (GridView)myRow.Parent.Parent; // the gridview
string ID = myGrid.DataKeys[myRow.RowIndex].Value.ToString();
GridViewRow rowSelect = (GridViewRow)selectBox.Parent.Parent;
int a = rowSelect.RowIndex;
ViewState["id"] = ID;
}
Try Following
Following Code may help u.
public void chkAssignee_OnCheckedChanged(object sender, EventArgs e)
{
CheckBox selectBox = (CheckBox)sender;
GridViewRow myRow = (GridViewRow)selectBox.Parent.Parent; // the row
GridView myGrid = (GridView)myRow.Parent.Parent; // the gridview
string ID = myGrid.DataKeys[myRow.RowIndex].Value.ToString();
GridViewRow rowSelect = (GridViewRow)selectBox.Parent.Parent;
int a = rowSelect.RowIndex;
ArrayList SelecterdRowIndices=new ArrayList();
if(ViewState["SelectedRowIndices"]!=null)
{
SelecterdRowIndices=(ArrayList)ViewState["SelectedRowIndices"];
bool flag=false;
foreach (int i in SelecterdRowIndices)
{
if(i==Convert.ToInt32(ID))
{
flag=true;
break;
}
}
if(!flag)
{
SelecterdRowIndices.Add(ID);
}
}
else
{
SelecterdRowIndices.Add(ID);
}
ViewState["SelectedRowIndices"] = SelecterdRowIndices;
}

Categories

Resources