Gridview textbox multi line only for one single case - c#

I am new to asp.net and I have a special issue,
I have to load a gridview from some database values...
I have 2 columns in my gridview one a label and one a textbox..
for a special value in the label the textbox should be multiline..for rest other cases the textmode should be single line...
can some one help me how to solve this issue??
PS: let me know if my question is not clear I can explain

You can use GridView.RowDataBound Event
Then find the value and if its match, you can change the property TextMode
protected void GVRowDataBound(object sender, GridViewRowEventArgs e)
{
var txb= (TextBox) e.Row.FindControl("TextBoxID");
}

You said ur new, so if in case you didn't know how to convert bound field to template field , follow this turtorial:
Tutorial
once u convert to template filed then on RowDataBound do like this:
void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e)
{
foreach (GridViewRow gRow in GridView1.Rows)
{
TextBox myfieldtxt = gRow.FindControl("yourTxtBxID") as TextBox;
Label myLable = gRow.FindControl("yourLableID") as Label;
if(myLable.Text.Equals("XYZ"))
{
myfieldtxt.TextMode = TextBoxMode.MultiLine;
}
else
{
myfieldtxt.TextMode = TextBoxMode.Single;
}
}
}

You can try this way:
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" ReadOnly="True" Text='Sometext'
TextMode="MultiLine"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>

Related

Getting the Contents of a Gridview in Row Command

This is the code in UI
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btn" runat="server" CommandName="Edit" Text="AFE" />
</ItemTemplate>
</asp:TemplateField>
--</Columns>
I Want to Get the Details of All Fields in Text boxes in Same page when ever I click on the Button Edit. I Tried using :
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Edit")
{
GridViewRow Row = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
string text = Row.Cells[2].Text;
}
But I am getting "" in string text..
This is screenshot of my grid view
You can use the row index stored in command argument to find a row where Edit button is clicked.
Now you can find the TextBox in that row where cell index location is 2.
Then get the Text of your TextBox.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName == "Edit")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow clickedRow = CustomersGridView.Rows[index];
TextBox myTextBox = (TextBox)clickedRow.Cells[2].FindControl("TextBoxName");
string text = myTextBox.Text;
}
}
In ASPX page, you need to handle row command event like this:
<asp:gridview id="GridView1"
datasourceid="DataSource"
autogeneratecolumns="false"
onrowcommand="GridView1_RowCommand"
runat="server">
</asp:gridview>
You can access to GridViewRow using following code (note: the Button must be the control that has CommandName/CommandArgument):
var row = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
Then simply use FindControl method on found row to find your target control, for ex.:
var txtSomething = (TextBox)row.FindControl("txtSomething");
Also you can access to RowIndex using row.RowIndex.
I recommended avoid using row.Cells[INDEX].FindControl(), just row.FindControl works just fine, targeting specific cell isn't good, if you change the markup and add/remove some columns, (maybe) you need to update the INDEX too, so don't do that :)
You need to find the TextBox control in the cell and get the value from it.
string text = (TextBox)Row.FindControl["MyTextBoxId"].Text;

GridViewRow Cells returning empty strings in button Click Event fire-up inside Gridview

I am confused with this problem.
I have put a button in side the template field of a gridview and want to return the data from that specific GridView Row when that corresponding button is clicked.
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="Button2" CssClass ="btnSkin" runat="server" Text="Answer" Width="117px" onclick="Button2_Click" />
</ItemTemplate>
</asp:TemplateField>
In the button click event fireup, I want to read that data by creating a GridViewRow Element.
protected void Button2_Click(object sender, EventArgs e)
{
GridViewRow gvr = (GridViewRow)(sender as Control).Parent.Parent;
Label8.Text = gvr.Cells[1].Text;
Label10.Text = gvr.Cells[2].Text;
Label12.Text = gvr.Cells[3].Text;
}
Now the problem is, the GridViewRow Cells are returning empty strings.
What should I do?????
When using <asp:TemplateFields>, you actually need to find the text which is inside your controls such as <asp:Label> you used inside your <ItemTemplate>.
Cells won't have text, its the Controls inside the cells that have text.
So, If suppose , you have a Label inside one of your <ItemTemplate> as:
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("CustomerID") %>'>
</asp:Label>
</ItemTemplate>
Then access the Text of this Label control using below code in your button Click event:[ assuming, 2nd Column contains the above <ItemTemplate> defined ]
protected void Button2_Click(object sender, EventArgs e)
{
GridViewRow gvr = (GridViewRow)(sender as Control).Parent.Parent;
String str = ((Label)gvr.Cells[1].FindControl("Label1")).Text;
}
I found the reason behind the empty strings error.
Gridview.Cells[i].Text will return the string value only when it is a <asp:BoundField>
If it is a <asp:TemplateField> and you have some ASP control inside the <ItemTemplate>, you must follow the FindControl("<control_id>") approach.
Here, basically we look for the control object in that particular GridviewRow Cell by its ID and cast it into the corresponding Control Type. Now, we can use that as we call any other asp control from code-behind.
String str = ((Label)gvr.Cells[1].FindControl("Label1")).Text;
Try using GridView.RowCommand Event and refer the following link for the same
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowcommand.aspx
hope this helps you.
Please check whether you are binding the grid properly on Page Load.
if(!IsPostBack)
{
BindgridView();
}
Hope this helps..Give a try..

How to Pass TextBox input to a gridview in asp.net?

I have two textbox and one gridview in my webform. The gridview is binded with database. But I want to add one more column on runtime which will be the textbox input from the webform. Because the scenario is like: I am maintaining two formula to calculate some percentage using the two textbox and the client wants to see this calculation for each row in the gridview.
But I cannot do this.
Is there anyone who can help me on this please? May be some suggestion.
Thanks in advance.
You could add the column in your GridView markup with a label control to display the result as follows.
Here is the markup needed, please note Visible is set to false.
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField Visible="false">
<ItemTemplate>
<asp:Label ID="label1" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Use the RowDataBound event to find the label and calculate your result as below:
void GridView1GridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
//find the control
var label1 = e.Item.FindControl("label1") as Label;
if (label1 != null)
{
if (!string.IsNullOrEmpty(tbInput1.Text) && !string.IsNullOrEmpty(tbInput2.Text))
{
// Do the calculation and set the label
label1.Text = tbInput1.Text + tbInput2.Text;
// Make the column visible
GridView1.Columns[0].Visible = true;
}
}
}
}
Please forgive any errors, I have not tested the above.

GridView row won't disable

I am trying to disable a specific grdview row using the code below, but it isn't disabling that row. I am 100% sure there is a value called "Total Expenses" in the column that is bound to the gridview. What is more strange is that, I removed the if condition(accountTextBox.Text == "Total Expenses") to see if all the rows get disabled but only the first row is getting disabled. Any thoughts on this?
More information: Am using gridview with template fields(ASP.NET, C#). I also ran debugger and found that the accountTextBox is showing NULL. Am puzzled!
I appreciate any thoughts you may have. Thank you
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
if (!tableCopied)
{
originalDataTable = ((System.Data.DataRowView)e.Row.DataItem).Row.Table.Copy();
ViewState["originalValuesDataTable"] = originalDataTable;
tableCopied = true;
TextBox accountTextBox = (TextBox)e.Row.FindControl("AccountTextBox");
if (accountTextBox.Text == "Total Expenses")
{
e.Row.Enabled = false;
}
}
}
I'm assuming your markup looks something like this:
<asp:TemplateField HeaderText="SomeField" SortExpression="SomeField">
<EditItemTemplate>
<asp:TextBox ID="AccountTextBox" runat="server" Text='<%# Bind("SomeField") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("SomeField") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
In which case AccountTextBox will only be available in RowDataBound when e.Row.State is in Edit mode. which may or may not be available depending what update functionality is provided in your datasource...but that's something else.
Typically you don't use a TextBox to display data but lets say trying to populate a "readonly" TextBox then all you need do is move AccountTextBox from the EditTemplate to the ItemTemplate and you should be good to go.
Using the following code-behind:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
gvTest.DataSource = new List<string>() { "test1", "test2" };
gvTest.DataBind();
}
private bool tableCopied = false;
private System.Data.DataTable originalDataTable;
protected void gvTest_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
if (!tableCopied)
{
//originalDataTable = ((System.Data.DataRowView)e.Row.DataItem).Row.Table.Copy();
//ViewState["originalValuesDataTable"] = originalDataTable;
//tableCopied = true;
TextBox accountTextBox = (TextBox)e.Row.FindControl("AccountTextBox");
if (accountTextBox.Text == "Total Expenses")
{
e.Row.Enabled = false;
}
}
}
}
And this markup:
<asp:GridView runat="server" ID="gvTest" OnRowDataBound="gvTest_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="AccountTextBox" runat="server">Total Expenses</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I am not reproducing the bug. Both rows disable for me.
The tableCopied variable could be the problem. It will be set to true on the first row and this will restrict the remaining rows to enter the if condition and actually be disabled.
First row:
//tableCopied is false
if(!tableCopied) // pass
tableCopied = true
Other rows:
//tableCopied is true
if(!tableCopied) // wont pass
Note that the GridView1_RowDataBound event occurs once for every row on the same postback and every class member is persisted during the postback.

How can I get the selected value from dropdownlist in edit mode of a gridview?

In my application, when I edit a row in the gridview I choose some new data from a dropdownlist.
I am populating the dropdown like this:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList emailsListDL = (DropDownList)e.Row.FindControl("emailsDL");
emailsListDL.DataSource = allUsersEmails;//list of strings with the emails of the users
emailsListDL.DataBind();
}
}
}
But when I press the 'Update' button from the template and enters in the 'RowUpdating' event, the selected value from the dropdownlist is every time the first value from that dropdownlist.
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
DropDownList emailsListDL = (DropDownList)GridViewAdvertisers.Rows[e.RowIndex].FindControl("emailsDL");
string email = emailsListDL.SelectedValue; //the selected value is every time the first value from the dropdownlist
}
Does anyone have any ideas?
I've tried many ways to set the selected value in the 'RowDataBound' event, but with no luck. I tried this:
1. emailsListDL.SelectedIndex = emailsListDL.Items.IndexOf(emailsListDL.Items.FindByValue(DataBinder.Eval(e.Row.DataItem, "OwnerMail").ToString()));
2. emailsListDL.SelectedValue = GridViewAdvertisers.DataKeys[e.Row.RowIndex]["OwnerMail"].ToString();
3. emailsListDL.SelectedValue = GridViewAdvertisers.Rows[e.Row.RowIndex].Cells[1].Text;
//ownerMail is a string (object) from the list of objects that I put as datasource to the gridview
Thanks,
Jeff
Update
My Item template from the aspx page is:
<asp:TemplateField ItemStyle-HorizontalAlign="Center" ItemStyle-VerticalAlign="Middle"
ItemStyle-Width="150px" HeaderText="Owner Email" HeaderStyle-HorizontalAlign="Left"
HeaderStyle-BorderWidth="1px" HeaderStyle-BorderColor="#e1e1e1">
<ItemTemplate>
<asp:Label ID="LabelEmail" runat="server" Text='<%# Bind("OwnerMail")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="emailsDL" runat="server" Width="150">
</asp:DropDownList>
</EditItemTemplate>
<HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" Font-Bold="True"></HeaderStyle>
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="180px" BorderWidth="1px"
BorderColor="#e1e1e1"></ItemStyle>
</asp:TemplateField>
The SelectedIndex will always default to 0 if you don't define it in your DropDownList definition.
Edit: #Tim Schmelter should add his comment as an anwer. In the meantime, I'll paraphrase for other readers: You need to check for postback (see comments above).
You can declare a ComboBox mainBX = new Combobox();
and you can declare an event
private void onSeletedIndexChange(object sender,EventArgs e)
{
mainBX = (ComboBox)(sender);
}
and next you should iterate foreach ComboBox in GridView and Add this Event .
Than all you should do is ,take the mainBX.seletedItem();
I think this is what you need ,if not apologise .
To set the Selected Value in the RowDataBound-Event, you should do it like this:
(DropDownList)e.Row.Cells[/*index*/].Controls[/*index, or use FindControl*/]).Items.FindByValue(((DataRowView)e.Row.DataItem).Row.ItemArray[/*columnnumber*/].ToString()).Selected = true;
FindByValue finds the current Textvalue of the Field in the "normal" Viewmode and sets the DropDownList with the value.
Of course this needs to be encapsulated in
if ((e.Row.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
{
}
As for your "getting the Value at Update"-Problem, I must honestly say I've got no clue, since your approach is exactly like mine, only difference: mine works.
Here's my code if it's any help:
protected void gridVariables_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string control = ((DropDownList)gridVariables.Rows[e.RowIndex].Cells[3].Controls[1]).SelectedValue;
gridVariables.EditIndex = -1;
this.gridVariables_DataBind(control, e.RowIndex);
}
private void gridVariables_DataBind(string control, int index)
{
DataTable dt = (DataTable)Session["variableTable"]; //features a DataTable with the Contents of the Gridview
dt.Rows[index]["ControlType"] = control;
gridVariables.DataSource = dt;
gridVariables.DataBind();
}
I had the same problem with a different solution, I had implemented custom paging on the GridView with a custom pager, and in the process added the RowCommand method, which was rebinding the grid with a new page index. As it happens though the RowCommand method is also called during Updating.
So be sure to check any other locations you may be binding anywhere in your code.
Hope this helps somebody else.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
string commandName = e.CommandName;
switch (commandName)
{
case "Page1":
HandlePageCommand(e);
//binding should happen here
break;
}
//this line is in the wrong location, causing the bug
BindGrid1();
}

Categories