Check if a column with a given name exists in a datarow - c#

How can I check if a column exists in result that populate a listview?
The listview is populated from a stored procedure.
This is what I tried but no success:
<%# Container.DataItem.GetType().GetProperty("Phone")==null?"phone is null":"we have phone property" #>
or should I use e instead Container.DataItem ?

First, i would use codebehind if it's getting complicated (i use it almost always). Here i would use the ListView's ItemDataBound event which is triggered for every item:
protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
// assuming you have an ItemTemplate with a label where you want to show this
Label lblInfo = (Label) e.Item.FindControl("LblInfo");
DataRowView rowView = (DataRowView)e.Item.DataItem;
if (rowView.Row.Table.Columns.Contains("Phone"))
{
lblInfo.Text = "we have the phone property";
}
else
{
lblInfo.Text = "no phone available";
}
}
}
That makes the code much more readable, maintainable, debuggable and type safe.

You can check this in OnItemDataBound.
protected void lstSample_OnItemDataBound(object sender, ListViewItemEventArgs e)
{
Label lblText = null;
Boolean isColumnExists = false;
if (e.Item.ItemType == ListViewItemType.DataItem)
{
DataRowView dr = (DataRowView)e.Item.DataItem;
isColumnExists = dr.DataView.Table.Columns.Contains("Hello");
lblText = (Label)e.Item.FindControl("lbltext");
if (isColumnExists)
{
lblText.Text = dr.Row["Hello"].ToString();
}
else
{
lblText.Text = dr.Row["Movies"].ToString();
}
}
}
Hope this helps!

Also, I found a solution:
public bool CheckProperty(string property_name)
{
try
{
Eval(property_name);
}
catch { return false; }
return true;
}

Related

ASP.NET Formview Textbox value- Object reference not set to an instance of an object

I would like to know whether or not this control is null once the page loads before I perform another operation. At the moment it just throws the object reference error.
protected void FormView1_DataBound(object sender, EventArgs e)
{
if (FormView1.CurrentMode == FormViewMode.ReadOnly)
{
string cname =
(this.FormView1.FindControl("companyname") as
System.Web.UI.WebControls.TextBox).Text;
if (cname == null)
{
}
else{
}
}
}
check for textbox first (make sure thats the ID youre looking up), something like,
TextBox compName = (Textbox)this.FormView1.FindControl("companyname");
string cName = "";
if(compName != null)
{
cName = compName.Text;
}
else
{
// textbox not found! do something?
}

gridview button

I apologize if this is a real simple question, but I can't find anyone else to ask. I have a gridview with a button column. I'm trying to use the button column to send a filename to another page. I pulled this code off of another solution here, but I get an error: "Does not contain a definition for 'Item'" on this line: ListViewDataItem item = (ListViewDataItem)e.Item; and I have no idea which Using-namespace (is that what they are called?) to use.
protected void gvFiles_RowCommand(object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e)
{
if (e.CommandName == "edit")
{
ListViewDataItem item = (ListViewDataItem)e.Item;
int index = item.DataItemIndex;
string fileID = ((ListView)sender).DataKeys[index]["fileID"].ToString();
Response.Redirect("irMain.aspx?#filename=" + fileID);
}
}
I suppose you are dealing with a gridView not a ListView, then the code should be
protected void gvFiles_RowCommand(object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e)
{
if (e.CommandName == "edit")
{
int index = Convert.ToInt32(e.CommandArgument);
string fileID = ((GridView)sender).DataKeys[index]["fileID"].ToString();
Response.Redirect("irMain.aspx?#filename=" + fileID);
}
}

Create session in gridview cell

i have a gridview with tempaltefield buttons,
i want to create a session with value of a cell in selected button row ,
can anyone help me i tryed this but didnt work:
protected void ImageButton1_Click1(object sender, ImageClickEventArgs e)
{
Session["mysession"] = GridView1.SelectedRow.Cells[1].Text;
}
First of all, if it's just a imagebutton in a templatefield, actually you don't select de row. This line will problably throw an exception because SelectedRow is null.
But if you are using a command to select, that's correct. Maybe your event (ImageButton1_Click1) is not assigned to your image (OnClick).
You can try something like this:
protected void Page_Load(object sender, EventArgs e)
{
try
{
//Add and event RowDataBound
grvGrid.RowDataBound += new GridViewRowEventHandler(grvGrid_RowDataBound);
}
catch
{
//...throw
}
}
protected void grvGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.Header)
{
//...
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Add an ImageButton foreach row in GridView
ImageButton ibtImageAlt = new ImageButton();
ibtImageAlt.ImageUrl = "App_Images/y.gif";
//ImageButton's ID will be the index of the row
ibtImageAlt.ID = e.Row.RowIndex.ToString();
ibtImageAlt.ForeColor = System.Drawing.Color.White;
ibtImageAlt.Font.Overline = false;
ibtImageAlt.Click += ibtImageAlt_Click;
}
}
catch
{
//...throw
}
}
protected void ibtImageAlt_Click(object sender, EventArgs e)
{
try
{
//Catch the ImageButton ID and the row in GridView
//An example to catch the value of the row selected by the ImageButton
Int32 intIndexRow = Convert.ToInt32(((ImageButton)sender).ID);
String strTest = grvGrid.Rows[intIndexRow].Cells[0].Text;
}
catch
{
//...throw
}
}

Binding dropdown list in a gridview edit item template

i can bind the dropdownlist in the edit item template. The drop down list is having null values.
protected void grdDevelopment_RowDataBound(object sender, GridViewRowEventArgs e)
{
DropDownList drpBuildServers = new DropDownList();
if (grdDevelopment.EditIndex == e.Row.RowIndex)
{
drpBuildServers = (DropDownList)e.Row.Cells[0].FindControl("ddlBuildServers");
}
}
also getting an error
Failed to load viewstate. The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request. For example, when adding controls dynamically, the controls added during a post-back must match the type and position of the controls added during the initial request.
I had problems with find control, in the end I used a little bit of recursion to find the control:
private Control FindControlRecursive(Control root, string id)
{
if (root.ID == id)
{
return root;
}
foreach (Control c in root.Controls)
{
Control t = FindControlRecursive(c, id);
if (t != null)
{
return t;
}
}
return null;
}
Then to find your control make this call:
drpBuildServers = (DropDownList) FindControlRecursive(e.Row.Cells[0], "ddlBuildServers");
protected void grdDevelopment_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList drpBuildServers;
drpBuildServers = e.Row.FindControl("ddlBuildServers") as DropDownList;
if (drpBuildServers != null)
// Write your code here
}
}
try http://www.codeproject.com/KB/webforms/editable_gridview_control.aspx , it could be helpful
Its a solution for me:
protected void grdDevelopment_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList drpBuildServers;
drpBuildServers = e.Row.FindControl("ddlBuildServers") as DropDownList;
if (drpBuildServers != null)
// Write your code here
}
}

ASP.NET dynamically created textbox doesn't change value

I have the following issue:
I create a TextBox dynamically in my web page, its value is "initialVal" in the beginning.
Now I need to make a postback (not callback) to the server, and during this operation, I need to compute/change the value of my textbox to other value.
Here's an example:
protected void Page_Load(object sender, EventArgs e)
{
TextBox txtBox = new TextBox();
txtBox.ID = "newButton";
form1.Controls.Add(txtBox);
txtBox.Text = "initialVal";
if (IsPostBack && Session["change"] == null)
{
txtBox.Text = "change";
Session["change"] = true;
}
}
The problem: even if I change the value via code, the textbox will keep the text "initialVal". I feel this is something related to the view state, but I don't understand.
Coudl anyone please help me here?
Thanks.
Everytime you load the page it is running this:
txtBox.Text = "initialVal";
You should wrap this in a check for postback:
if (!Page.IsPostback)
{
txtBox.Text = "initialVal";
}
That said, onLoad is the wrong event to do the creation, for it to be valid in the early enough in the page lifecycle, use OnInit.
See this article on MSDN.
Here is the final code from #user2890888:
public partial class WebForm1 : System.Web.UI.Page
{
TextBox txtBox = null;
protected void Page_Init(object sender, EventArgs e)
{
txtBox = new TextBox();
txtBox.ID = "newButton";
form1.Controls.Add(txtBox);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
txtBox.Text = "initialVal";
}
if (IsPostBack && Session["change"] == null)
{
txtBox.Text = "change";
Session["change"] = true;
}
}
}
Create your dynamic textbox creation in !IsPostBack
protected void Page_Load(object sender, EventArgs e)
{
if(!isPostBack){
TextBox txtBox = new TextBox();
txtBox.ID = "newButton";
form1.Controls.Add(txtBox);
txtBox.Text = "initialVal";
}
if (IsPostBack && Session["change"] == null)
{
txtBox.Text = "change";
Session["change"] = true;
}
}
Thanks and let me know if your issue still pending
Find the TextBox and use it
TextBox txtBox = (TextBox)FindControl("txtBox");
txtBox.Text = "change";
Even now you are having issue and your textBox is not getting the value you needed.
Store your new value for TEXTBOX in a hiddenfield.
I mean ,
if (IsPostBack && Session["change"] == null)
{
hiddenfield1.value = "change";
}
and later in your page script, you can assign back the value in this hiddenfield1 to textbox.
$(document).ready(
{
$('#txtBoxID').value=$('#hiddenfield1').value;
}
);

Categories